在Python中定义函数。
1. 比如用Python写一个斐波那契数列函数:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
函数调用:
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
在Python函数中,def关键字声明一个函数定义,函数名称紧跟其后,函数名称后面是包含参数列表的小括号,最后是冒号结尾。
然后Python函数的函数体从下一行开始,必须注意要有字符缩进。
Python的函数调用,比如:
>>> fib(0)
>>> print(fib(0))
None
2. fib(n)是没有返回值的函数,下面写一个有返回值的Python函数,返回[]list列表:
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
函数调用:
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
函数fib2(n)实例中展示了新的Python feature,其中return用于声明当前函数返回一个值,result.append(a)调用了list对象result的append函数,append是由对象的类型决定的函数,实际上相当于result = result + [a],但是append的效率更高。
3. 在Python函数定义中定义多个参数列表,以及为参数赋上默认值:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
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 ValueError('invalid user response')
print(reminder)
这里又个非常重要的警告,需要在实际项目中多加注意!!默认值通常只计算一次,但是如果默认值是可变的,比如list,就会有如下情况:
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
4. 函数里的关键字参数
形式是kwarg=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 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)
for kw in keywords:
print(kw, ":", keywords[kw])
5. 特殊参数
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
| Positional or keyword |
| - Keyword only
-- Positional only
6. 注意函数的代码风格和命名规范
比如使用4个空格键为不是tab缩进等。