标签:height pre day 运行 image ## alt nbsp ...
In [3]: def divid(a,b): ...: shang = a//b ...: yushu = a%b ...: return shang,yushu ...: In [4]: sh, yu = divid(5,2) #元组方式返回 (2,1) In [5]: sh Out[5]: 2 In [6]: yu Out[6]: 1
缺省参数,使用默认的值,
只能放到最后
命名参数,必须使用形参的变量名a,b,c
#### 两天的营业额 def add(a,b): result = a + b print(result) add(11,22)
我想把每天的营业额加起来,但是有时开业5天,有时候开业7天
变量就是args 只不过加了标记*
元组:切记一个元素的写法(33,)
def add(a,b,*args): print("------") print(a) print(b) print(args) #result = a + b #print(result) add(11,22,55,66,77,88) #(55,66,77,88) add(11,22,33) #(33,) add(11,22) #() add(11) #报错 形参b没有值
计算多个数的值
1)版本1:我的
def add(a,b,*args): result = a + b print(a,b,args) for temp in args: result = temp + result print(result) add(1,12,23,34,45,55,66,77,88,99)
2)版本2:老师的
def add(a,b,*args): print("-"*30) print(a) print(a) print(*args) result = a+b for temp in args: result += temp print("result=%d"%result) add(11,22) add(11,22,33) add(11,22,33,44,55,66)
#最复杂的带参数的 def test(a,b,c=33,*args,**kwargs): print(a) #必须传递的参数a,b print(b) print(c) #可选的 c print(args) #*多余的没有名字的 args print(kwargs) #**多余的有名字的 kwargs test(11,22,33,44,55,66,task=99,done=98)
把元组拆成一个个,当成参数传递
把字典拆成一对对键值对,当成参数传递
###### 拆包之前 def test(a,b,c=33,*args,**kwargs): print(a) print(b) print(c) print(args) print(kwargs) #test(11,22,33,44,55,66,task=99,done=98) A = (44,55,66) B = {"name":"alex","age":18} test(11,22,33,A,B) #### 运行结果 11 22 33 ((44, 55, 66), {‘age‘: 18, ‘name‘: ‘alex‘}) #A,B是传递的参数 {} #没有传入命名参数
#### 拆包之后 def test(a,b,c=33,*args,**kwargs): print(a) print(b) print(c) print(args) print(kwargs) #test(11,22,33,44,55,66,task=99,done=98) A = (44,55,66) B = {"name":"alex","age":18} test(11,22,33,*A,**B) #### 运行结果 11 22 33 (44, 55, 66) {‘age‘: 18, ‘name‘: ‘alex‘}
标签:height pre day 运行 image ## alt nbsp ...
原文地址:http://www.cnblogs.com/venicid/p/7865840.html