Python复习笔记—函数

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.
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值