1、函数定义:
1 def test(): 2 "the funcation details" 3 print("in the test funcation") 4 return 0
def #定义函数的关键字
test #函数名
() #定义形参,我这边没有定义。如果定义的话,可以写成:def test(x): 其中x就是形式参数
"the funcation details" # 文档描述(非必要,但是强烈建议你为你的函数添加详细信息,方便别人阅读)
print #泛指代码块或者程序逻辑处理
return #定义返回值
2、过程定义:
1 def test_2(): 2 "the funcation details" 3 print("in the test funcation")
注:从上面两个例子看出来,函数和过程,无非就是函数比过程多了一个return的返回值,其他的也没什么不一样。
3、两者比较:
#定义函数
1 def test_1(): 2 "the funcation details" 3 print("in the test funcation") 4 return 0
#定义过程
1 def test_2(): 2 "the funcation details" 3 print("in the test funcation") 4 5 a = test_1() 6 b = test_2() 7 print(a) 8 print(b)
#输出
in the test funcation
in the test funcation
#输出返回值
0
#没有return ,返回为空
None
小结:不难看出,函数和过程其实在python中没有过多的界限,当有return时,则输出返回值,当没有return,则返回None
4、使用函数原因
使用函数主要好处:
- 代码重复利用
- 可扩展性
- 保持一致性
1)代码重复利用
① 优化前
1 #假设我们编写好了一个逻辑(功能),用来打印一个字符串 2 print("hello world!") 3 4 #现在下面有2个函数,每个函数处理完了,都需要使用上面的逻辑,那么唯一的方法就是拷贝2次这样的逻辑 5 def test_1(): 6 "the funcation details" 7 print("in the test1") 8 print("hello world!") 9 10 def test_2(): 11 "the funcation details" 12 print("in the test2") 13 print("hello world!")
那么假设有n个函数,我们是不是也要拷贝n次呐?于是,我们就诞生了下面的方法
① 优化后
1 def test(): 2 print("hello world!") 3 4 def test_1(): 5 "the funcation details" 6 print("in the test1") 7 test() 8 9 def test_2(): 10 "the funcation details" 11 print("in the test2") 12 test() 13 print(test_1()) 14 print(test_2())
2)可扩展,代码保持一致性
1 def test(): 2 print("修改输出hello haha") 3 4 def test_1(): 5 "the funcation details" 6 print("in the test1") 7 test() 8 9 def test_2(): 10 "the funcation details" 11 print("in the test2") 12 test() 13 print(test_1()) 14 print(test_2())
注:如果遇到代码逻辑变了,用以前拷贝n次的方法,那什么时候拷贝完啊,而且中间有遗漏怎么办,如果用了函数,我们只需要改这个函数的逻辑即可,不用改其他任何地方
5、返回值
1)return作用
return其实有两个作用:
- 需要用一个变量来接受程序结束后返回的结果
- 它是作为一个结束符,终止程序运行
1 def test(): 2 print("in the test_1") 3 return 0 4 print("the end") #结果中没有打印 5 6 x = test() 7 print(x) 8 9 #输出 10 in the test_1 #第一次打印 11 0 #结果返回值
注:从上面的代码可以看出,return 0后面的代码就不执行了,只执行return前面的代码;变量x接受了test()函数结束后的返回结果
2)返回多个值
1 def test_1(): 2 print("in the test_1") 3 4 def test_2(): 5 print("in the test_2") 6 return 0 7 8 def test_3(): 9 print("in the test_3") 10 return 1,"hello",["zhou","shuaigao"],{"name":"zhou"} 11 12 x = test_1() 13 y = test_2() 14 z =test_3() 15 print(x) 16 print(y) 17 print(z) 18 19 #输出 20 in the test_1 21 in the test_2 22 in the test_3 23 None #x的值 24 0 #y的值 25 (1, 'hello', ['zhou', 'shuaigao'], {'name': 'zhou'}) #z的值
从上面的例子可以看出:
- 没有定义,返回值数=0,返回:None
- 只定义了1个返回值,返回值=1 ,返回:定义的那个值,或者说定义的那个object
- 定义了2个以上,返回值 > 1,返回:1个元组(tuple)
提问:这边我们不经意的要问,为什么要有返回值?
因为我们想要这个函数的执行结果,这个执行结果会在后面的程序运行过程中需要用到。