函数的参数类型有:位置参数,默认参数,可变参数,关键字参数,命名关键字参数
1.位置参数
def power(x):
return x*x
power(1)
1
power(2)
4
power(0)
0
2.默认参数:默认参数必须指向不可变对象
def power(x,n=2):
sum=1
while n>0:
n=n-1
sum=sum*x
return sum
power(1)
1
power(2)
4
power(2,3)
8
3.可变参数
def calcs(*nums):
sum=0
for num in nums:
sum=sum+num
return sum
calcs(1,2,3,4,5)
15
l=[1,2,3,4,5]
calcs(*l)
15
t=(1,2,3,4,5)
calcs(*t)
15
4.关键字参数
def person(name,age,**kw):
print("name:",name,"age:",34,"others:",kw)
person("zhou hailong",23,city="suzhou",scores=99)
name: zhou hailong age: 34 others: {'city': 'suzhou', 'scores': 99}
others={"city":"suzhou","scores":99}
person("zhou hailong",24,city=["city"],scores=["scores"])
name: zhou hailong age: 34 others: {'city': ['city'], 'scores': ['scores']}
person("zhou hailong",25,**others)
name: zhou hailong age: 34 others: {'city': 'suzhou', 'scores': 99}
5.命名关键字参数
def person(name,age,*,city,scores):
print("name:",name,"age:",age,city,scores)
person("zhou hailong",24,city="suzhou",scores=88)
name: zhou hailong age: 24 suzhou 88
person("zhou hailong",24,city="suzhou",num=22)
Traceback (most recent call last):
File "<pyshell#315>", line 1, in <module>
person("zhou hailong",24,city="suzhou",num=22)
TypeError: person() got an unexpected keyword argument 'num'