# 学习Python 3000 - 1 函数定义

[b]定义函数 - def func():[/b]

def fib(n):    # write Fibonacci series up to n    """Print a Fibonacci series up to n."""    a, b = 0, 1    while b < n:        print(b, end=' ')        a, b = b, a+b        print()

[b][color=blue]def[/color] [/b]是函数定义关键字。后面跟函数名称和参数列表，以冒号结尾，另起一行，并缩进一个TAB开始函数正文。
#是单行注释，""" """ 是大块注释。
[color=blue][b]符号表（symbol table）[/b][/color]，[color=blue]a, b = 0, 1[/color] 这一句，将a b引入函数（fib）的局部符号表。注意，Python的变量寻找顺序：函数内部符号表，引用的其他函数的符号表，全局符号表，最后到系统内置（built-in）表里面找。函数的参数 （n），也放在这个函数（fib）的局部符号表里面。

[color=blue][b]None[/b][/color]，这个函数的返回值就是None，这里省略了return None。

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

[color=blue][b]

[b]为参数设定默认值 （Default Argument Values）[/b]
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 = 5def f(arg=i):    print(arg)i = 6f()

def f(a, L=[]):    L.append(a)    return Lprint(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

[b]关键字参数（Keyword Arguments）[/b] 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 missingparrot(voltage=5.0, 'dead')  # non-keyword argument following keywordparrot(110, voltage=220)     # duplicate value for argumentparrot(actor='John Cleese')  # unknown keyword

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120