首页 > 其他 > 详细

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

时间:2019-10-26 01:14:06      阅读:140      评论:0      收藏:0      [点我收藏+]

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只能是字符串
 

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

原文:https://www.cnblogs.com/snowony/p/11741566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!