学习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)的局部符号表里面。
当函数调用别的函数时,就会为被调函数创建一个新的符号表。调用函数只是将值传递给了被调函数,也就是说Python的函数调用参数是值传递。
函数的名称会被引入到当前的符号表中。
[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][/color]

[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 = 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

[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 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值