# Python: 深入Python函数定义

## 1. 默认参数值

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

• 只给出必要的参数： ask_ok(‘Do you really wnat to quit?’)
• 只给出一个可选的参数： ask_ok(‘Ok to overwrite the file’,2)
• 或者给出所有的参数： ask_ok(‘OK to overwrite the file?’,2,’Come on, only yes or no!’),

```
12345i = 5
def f(arg = i):
print(arg)
i = 6
f()

```

 123456 def f(a, L = []):     L.append(a)     return L print(f(1)) print(f(2)) print(f(3))

```
123[1]
[1, 2]
[1, 2, 3]

```

 12345 def f(a, L=None):     if L is None:         L = []     L.append(a)     return L

## 2. 关键字参数

 1 def parrot(voltage, state = 'a stiff', action = 'voom', type = 'Norwegian Blue'):

 123456 parrot(1000) parrot(voltage = 1000) parrot(voltage = 10000, action = 'VOOOM') parrot(action = 'VOOOOM', voltage = 1000) # action 写在前面也是OK的！ parrot('a million', 'bereft of life', 'jump') # voltage = 'a milion' parrot('a thousand', state = 'pushing up the daisies') # voltage = 'a thousand'

 1234 parrot() # voltage必须有值 parrot(voltage = 5.0, 'dead') # 一旦有一个参数是通过关键字指定的，后面的也必须都是 parrot(110, voltage = 220) # 两个voltage的值 parrot(acotr = 'Jonh Cleese') # 没有voltage的值

 123456789 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) # 打印40个’-‘     keys = sorted(keywords.keys()) # 按键值排序     for kw in keys:         print(kw, ":>", keywords[kw])

 12345 cheeseshop("Limburger>", "It's very runny, sir.>",            "It's really very, VERY runny, sir.>",            shopkeeper="Michael Palin>",            client="John Cleese>",            sketch="Cheese Shop Sketch>")

## 3. 可变参数列表

 12 def write_multiple_items(file, separator, *args):     file.write(separator.join(args)) # 用separator符号将arg里的内容连在一起

 1234567 >>> def concat(*args, sep="/>"): ...    return sep.join(args) ... >>> concat("earth>", "mars>", "venus>") 'earth/mars/venus' >>> concat("earth>", "mars>", "venus>", sep=".>") 'earth.mars.venus'

## 4. 参数列表的分拆

 12345 >>>list(range(3, 6)) [3, 4 ,5] >>> args = [3, 6] >>> list(range(*args)) [3, 4, 5]

 12345678 >>> def parrot(voltage, state='a stiff', action='voom'): ...     print("-- This parrot wouldn't>", action, end=' ') ...     print("if you put>", voltage, "volts through it.>", end=' ') ...     print("E's>", state, "!>") ... >>> d = {"voltage>": "four million>", "state>": "bleedin' demised>", "action>": "VOOM>"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

## 5. Lambda形式

 12345678 >>> def make_incrementor(n): ...     return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43