def fib(n):
'''do nothing'''
pass
def
定义函数,其后跟有函数名和以括号扩起来的形参列表。组成的函数体从下一行开始,且必须缩进。/** */
注释里的内容。return
语句的函数也会返回一个值None
。def ask_ok(prompt, retries=4, complaint='Yes or no'):
while True:
ok = raw_input(prompt)
print complaint
默认值在函数定义的时候计算,并且只计算一次,例如
i = 5
def f(arg=i):
print arg
i = 6
f() # output 5
当默认值是列表、字典或大部分实例时会有所不同。
def f(a, L=[]):
L.append(a)
return L
print f(1) # [1]
print f(2) # [1, 2]
print f(3) # [1, 2, 3]
解决方法如下
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
**name
形式的参数接受一个字典,而且必须位于*name
之后。
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, "?"
print "-- I'm sorry, we're all out of", kind
for arg in arguments:
print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
range(3, 6) # normal call with separate arguments
# output [3, 4, 5]
args = [3, 6]
range(*args) # call with arguments unpacked from a list
# output [3, 4, 5]
lambda局限于只能有一个单独的表达式。他们只是普通函数定义的语法糖。
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43