函数参数分类,如下:
def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
>>> power(5,3)
125
power(5) 相当于 power(5,2)
>>> power(5)
25
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
>>> calc(1,2)
5
>>> calc(1,2,3)
14
将现有的tuple或list当做可变参数传入函数:只需要在tuple或list前加上 * 即可
>>> list_1 = [1,2,3]
>>> calc(*list_1)
14
>>> tuple_1 = (1,2,3)
>>> calc(*tuple_1)
14
>>> def person(name,age,**kw):
... print(‘name:‘,name,‘age:‘,age,‘other:‘,kw)
### 函数调用
>>> person(‘花花‘,1.7)# 无关键字参数
name: 花花 age: 1.7 other: {}
>>> person(‘花花‘,1.7,city=‘杭州‘)#有一个关键字参数
name: 花花 age: 1.7 other: {‘city‘: ‘杭州‘}
>>> person(‘花花‘,1.7,city=‘杭州‘,gender=‘男‘)#两个关键字参数
name: 花花 age: 1.7 other: {‘city‘: ‘杭州‘, ‘gender‘: ‘男‘}
>>> extra = {‘city‘:‘杭州‘,‘gender‘:‘公‘}
>>> person(‘花花‘,1.7,**extra)#将预先定义好的dict当做关键字参数传到函数中
name: 花花 age: 1.7 other: {‘city‘: ‘杭州‘, ‘gender‘: ‘公‘}
*
后面的参数被视为命名关键字参数# 命名关键字参数的定义
>>> def person(name, age, *, city, job):
... print(name, age, city, job, sep=‘,‘)
#命名关键字参数的调用
>>> person(‘花花‘,1.7,city=‘杭州‘,job=‘play‘)
花花,1.7,杭州,play
>>> def person(name, age, *args, city, job):
... print(name, age, args, city, job, sep=‘,‘)
>>> person(‘花花‘,1.7,city=‘hangzhou‘,job=‘play‘)
花花,1.7,(),hangzhou,play
>>> person(‘花花‘,1.7,‘花花 is lovely‘,city=‘hangzhou‘,job=‘play‘)
花花,1.7,(‘花花 is lovely‘,),hangzhou,play
原文:https://www.cnblogs.com/wooluwalker/p/12240992.html