ningleesherry 发表于 2017-5-2 12:55:32

学习Python 3000

定义函数 - def func():

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()


def 是函数定义关键字。后面跟函数名称和参数列表,以冒号结尾,另起一行,并缩进一个TAB开始函数正文。
#是单行注释,"""""" 是大块注释。
符号表(symbol table),a, b = 0, 1 这一句,将a b引入函数(fib)的局部符号表。注意,Python的变量寻找顺序:函数内部符号表,引用的其他函数的符号表,全局符号表,最后到系统内置(built-in)表里面找。函数的参数 (n),也放在这个函数(fib)的局部符号表里面。
当函数调用别的函数时,就会为被调函数创建一个新的符号表。调用函数只是将值传递给了被调函数,也就是说Python的函数调用参数是值传递。
函数的名称会被引入到当前的符号表中。
None,这个函数的返回值就是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


定义不定个数的参数列表
为参数设定默认值 (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))

打印结果是





要想避免这种情况:

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
页: [1]
查看完整版本: 学习Python 3000