1. 函数的定义
>>> def foo() :
pass # function body
2. 变量的作用域
局部函数可以引用全局变量,但不能修改
>>> x = 15 >>> >>> def foo() : x = 13 >>> foo() >>> x 15 >>> def echox() : print x >>> echox() 15
3. 函数的返回值
函数如果没有显示返回值,则默认返回None
4. 默认参数
>>> def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_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 like python: ')
do you like python: yes
True
>>> ask_ok('do you like python: ', 2)
do you like python: d
Yes or no, please!
do you like python: a
Yes or no, please!
do you like python: s
Traceback (most recent call last):
File "<pyshell#283>", line 1, in <module>
ask_ok('do you like python: ', 2)
File "<pyshell#279>", line 10, in ask_ok
raise IOError('refusenik user')
IOError: refusenik user
>>>
>>> ask_ok('do you like python: ', 1, 'yes or no ?')
do you like python: l
yes or no ?
do you like python: y
True
5. 关键字参数
可以指定参数值
ask_ok(prompt='do u like python: ', complaint='yes or no?')
6. List参数和Dict参数
>>> 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]
>>> cheeseshop('cheese', 'one', 'two', 'three', one = 1, tow = 2)
-- Do you have any cheese ?
-- I'm sorry, we're all out of cheese
one
two
three
----------------------------------------
one : 1
tow : 2
7. Unpacking参数列表
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list, unpack by *
[3, 4, 5]
8. Lambda匿名的函数对象
>>> def inc(n) :
return lambda x : x + n
>>> inc(12)
<function <lambda> at 0x02227B30>
>>>
>>> f = inc(12)
>>> f(1)
13
>>> f(3)
15
>>> fn = inc(30)
>>> fn(9)
39
9. 自描述的文档
>>> def inc(n) :
"""
return a functor caculate increasement.
"""
return lambda x : x + n
>>>
>>> print inc.__doc__
return a functor caculate increasement.