# python中函数的参数

1. 位置参数
def power(x):
return x*x

2. 默认参数

def power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s

3. 可变参数

def calc(*numbers):
sum =0
for n in numbers:
sum = sum + n*n
return sum

>>>calc(1,2)
5
>>>calc()
0

4.关键参数

def person(name,age,**kw):
print('name:',name,'age:',age,'others':kw)

>>>person('Json',20)
name:Json age:20 others:{}
>>>person('Bob',35,city="Beijing")
name:Bob age:35 others:{'city':'Beijing'}

5.命名关键字参数

def person(name,age,*,city,job):
print(name,age,city,job)

>>>person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() takes 2 positional arguments but 4 were given

>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

7.参数列表

def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

Python的函数具有非常灵活的参数形态，既可以实现简单的调用，又可以传入非常复杂的参数。

*args是可变参数，args接收的是一个tuple；

**kw是关键字参数，kw接收的是一个dict。

• 本文已收录于以下专栏：

举报原因： 您举报文章：python中函数的参数 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)