您的位置:首页 > 其它

(7)函数

2015-06-07 11:03 295 查看
生成指定边界的斐波那契数列的函数:

def fib(n):
a,b=0,1
while a < n:
print(a,end=',')
a,b=b,a+b
fib(1000)


运行结果:

>>> ================================ RESTART ================================
>>>
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,


1.带有默认值的参数:
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 want to quit?')
给出一个可选的参数: ask_ok('OK to overwrite the file?', 2)
或者给出所有的参数: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')


2.关键字参数:key=value的形式调用:

示例1.

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(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword


示例2:引入一个形如 **name 的参数时,它接收一个字典,使用一个形如 *name 的形式参数,它接收一个元组。*name 必须在 **name 之前出现。
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)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])


调用:

>>> ================================ RESTART ================================
>>>
>>> cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>


3.可变参数列表:

def write_multiple_items(file, separator, *args):
file.write(separator.join(args))


调用:

>>> ================================ RESTART ================================
>>>
>>> def concat(*args, sep="/"):
return sep.join(args)

>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
>>>


lambda形式:

def make_incrementor(n):
return lambda x: x + n


运行:

>>> ================================ RESTART ================================
>>>
>>> f=make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: