zoe233

编程方法的有主要以下三类方法:

  1.面向对象

  2.面向过程

  3.函数式编程——最早的编程方法,目前又重新进入了大家的视野。

这三种编程方式,都是编程的方法论,编程的规范。

 

编程方法“门派论”(为了更好的理解)

  1.面向对象——华山派-->独门秘籍:类-->class

  2.面向过程——少林派-->独门秘籍:过程-->def   

  3.函数式编程——逍遥派-->独门秘籍:函数-->def  

 

 


 

函数的定义:

  1.数学意义上的函数定义:给定一个数集A,对A施加对应法则f,记作f(A),得到另一数集B,也就是B=f(A).那么这个关系式就叫函数关系式,简称函数.

例:设数集A={1、2、3、4、5},对A施加对应法则求平方,得B={1、4、9、16、25}也就是B=f(A)=A^2,这个关系式就是函数。

  2.函数是一种逻辑结构化和过程化的一种方法。

  Python中函数的定义方法:

  

  定义函数需要注意的几个事项:

    1、def开头,代表定义函数
    2、def和函数名中间要敲一个空格
    3、之后是函数名,这个名字用户自己起的,方便自己使用就好
    4、函数名后跟圆括号(),代表定义的是函数,里边可加参数
    5、圆括号()后一定要加冒号: 这个很重要,不要忘记了
    6、代码块部分,是由语句组成,要有缩进
    7、函数要有返回值return

 

为什么要使用函数?

好处:1.减少代码量,可重复利用;2.可拓展;3.保持一致性

在程序中如果有可以重复利用的逻辑一定要使用函数。另外函数都要加上函数说明。

 

 1 import time
 2 def logger():
 3     time_format=\'%Y-%m-%d %X\'
 4     time_current=time.strftime(time_format)
 5     with open(\'a.txt\',\'a+\') as f:
 6         f.write(\'%s end action\n\'%time_current)
 7 
 8 def test1():
 9     \'函数描述\'
10     print(\'in the test1\')
11     logger()
12 
13 def test2():
14     \'函数描述\'
15     print(\'in the test2\')
16     logger()
17 
18 def test3():
19     \'函数描述\'
20     print(\'in the test3\')
21     logger()
22 test1()
23 test2()
24 test3()
25 \'\'\'好处:
26 1.代码的重复利用
27 2.可拓展
28 3.保持一致性
29 \'\'\'

 

 return的作用——为什么要有返回值?

1.结束函数;

2.将返回值赋值到对象中,可以调用函数的结果

return返回的值如果有多个,可以将其组合成一个元组返回,如:

 1 def test1():
 2     \'no return value\'
 3     print(\'return value in test1\')
 4 
 5 def test2():
 6     \'return value2\'
 7     print(\'return value in test2\')
 8     return 2
 9 
10 def test3():
11     \'return a lot of values in tuple\'
12     print(\'return value in test3\')
13     return 1,{1},(1),[1,],{1:1}
14 
15 a=test1()
16 b=test2()
17 c=test3()
18 print(a)
19 print(b)
20 print(c)

返回:

 

 

 

 

 


 

面向过程——少林派-->独门秘籍:过程-->def  |   函数式编程——逍遥派-->独门秘籍:函数-->def:

过程就是没有返回值的函数

 1 #定义函数
 2 def func1():
 3     \'定义函数\'
 4     print(\'in the func1\')
 5     return 0
 6 
 7 x=func1()
 8 
 9 #定义过程
10 def func2():
11     \'定义过程\'
12     print(\'in the func2\')
13 
14 y=func2()

在Python中定义函数和定义过程的区别不大:

 1 #定义函数
 2 def func1():
 3     \'定义函数\'
 4     print(\'in the func1\')
 5     return 0
 6 
 7 x=func1()  #向屏幕输出 print(\'in the func1\')
 8 print(x)  #返回0
 9 
10 #定义过程
11 def func2():
12     \'定义过程\'
13     print(\'in the func2\')
14 
15 y=func2() #向屏幕输出 print(\'in the func2\')
16 print(y)  #返回None

 

分类:

技术点:

相关文章:

  • 2021-11-23
  • 2021-11-28
  • 2021-04-09
  • 2021-10-09
  • 2022-12-23
  • 2021-08-23
猜你喜欢
  • 2021-12-03
  • 2021-10-17
  • 2022-12-23
  • 2021-07-13
  • 2022-12-23
  • 2022-01-04
相关资源
相似解决方案