函数(定义,有无返回值,参数以及传参问题)


1.定义
def test():
x+=1
return x
好处:*减少代码重用
*保持一致性和易维护性
*可扩展性
2.关于有无返回值
无:过程就是没有返回值的函数
有:一个————返回本身
def test():
s=[5,4,32,556,22]
return s
print(test())
#打印结果 [5, 4, 32, 556, 22]
多个————返回元祖
def test():
l=[5,4,32,556,22]
s='fjy'
return l,s
print(test())
##打印结果 ([5, 4, 32, 556, 22], 'fjy')
3.参数
**形参只有调用时才会执行,遇到时只进行编译。
一个函数碰到一个return就结束
1.位置参数必须一一对应,缺一不可
def test(x,y,z):
print(x)
print(y)
print(z)
test(1,2,3)
2.关键字参数,无须一一对应,缺一不行多一也不行
def test(x,y,z):
print(x)
print(y)
print(z)
test(y=1,x=3,z=4)
3.混合使用,位置参数必须在关键字参数左边
test(1,y=2,3)#报错
test(1,3,y=2)#报错
test(1,3,z=2)
******一个参数不能传两个值
test(1,3,z=2,y=4)#报错
4.参数组:**字典 --关键字参数
*元祖 --可变参数
(*遍历的意思,打印多个参数转换为元祖)
def test(x,*args):
print(x)
print(args)
test(1) #打印结果:1
test(1,2,3,4,5) #打印结果: 1 (2, 3, 4, 5)
test(1,{'name':'alex'}) #打印结果: 1 ({'name': 'alex'},)
test(1,['x','y','z']) #打印结果: 1 (['x', 'y', 'z'],)
test(1,*['x','y','z']) #打印结果: 1 ('x', 'y', 'z')
test(1,*('x','y','z')) #打印结果: 1 ('x', 'y', 'z')

def test(x,**kwargs):
print(x)
print(kwargs)
test(1,y=2,z=3) #打印结果:1 {'y': 2, 'z': 3}
test(1,**{'y':5,'z':3}) #结果: 1 {'y': 5, 'z': 3}
**在这里key只能是字符串
 

猜你喜欢

转载自www.cnblogs.com/snowony/p/11741566.html