def fib2(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
result = []
while b < n:
result.append(b)
a, b = b, a+b
return result
定义不定个数的参数列表 为参数设定默认值 (Default Argument Values)
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)
注意,默认值,是在定义的时候就计算出来的,如下:
i = 5
def f(arg=i):
print(arg)
i = 6
f()
会打印出5,而不是6.
注意,默认值,只初始化一次。如下
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
打印结果是
[1]
[1, 2]
[1, 2, 3]
要想避免这种情况:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
关键字参数(Keyword Arguments) keyword = value
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
可以这么调用:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
但不能这样:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword