1、函数
定义函命名:①遵守变量命名规则 ②尽量做到见名知意 ③驼峰规则
参数类型:
定义 而言可以分为
①必备参数
>>> def fun1(a):
print(a)
调用时必须传参数,不能多不能少
>>> fun1(5)
5
②默认参数
>>> def fun2(b=1):
print(b)
调用时可传可不传参数,可指定
>>> fun2()
1
>>> fun2(5)
5
>>> fun2(b=2)
2
③不定长参数
>>> def fun3(*arg):
print(arg)
调用时可以随意传参数,把传入参数包装成元组,调用时加‘*’会解包,字典只取key。
>>> fun3(1,2,3)
(1, 2, 3)
>>> fun3([1,2,3])
([1, 2, 3],)
>>> fun3(*[1,2,3])
(1, 2, 3)
>>> def fun4(**kwarg):
print(kwarg)
调用时可传可不传参数,属于关键字参数,把传入参数包装成字典,加‘**’可以传入字典
>>> fun4(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> fun4(**{'d': 11, 'e': 22, 'f': 33})
{'d': 11, 'e': 22, 'f': 33}
参数混合使用时
定义时必备参数必须在默认参数之前,确保必备参数拿到值,也不能多拿
调用时必备参数在默认参数前面,关键字参数在最后
2、return的作用 #print返回值为None
返回函数的结果、是函数结束的标志。除了赋值语句,其他都能接。
>>> def fun5(a,b):
if a > b:
return 'a比b大'
elif a < b:
return 'b比a大'
else:
return 'a等于b'
>>> fun5(2,3)
'b比a大'
3、lambda函数 匿名函数
lambda x:x+1
x是参数,x+1是返回值