python-07

一、函数
引用:例,定义一个foo函数,然后让bar引用foo 
  1. >>> def foo(): print 'hello world!'
  2. ...
  3. >>> bar = foo
  4. >>> bar()
  5. hello world!
  6. >>> foo()
  7. hello world!

二、关键字参数
例:func1需要有一个参数,该参数必须提供,否则出现异常
  1. >>> def func1(x):
  2. ... print '
  3. KeyboardInterrupt
  4. >>> def func1(x): print '*' * x
  5. ...
  6. >>> func1()
  7. Traceback (most recent call last):
  8. File "<stdin>", line 1, in <module>
  9. TypeError: func1() takes exactly 1 argument (0 given)
  10. >>> func1(5)
  11. *****
例2:如何提供了多个值,这些值将依次传递给每个参数。值的数目要求和参数否则仍然有错误。
  1. >>> def func2(x, y): print x * y
  2. ...
  3. >>> func2(3, 4)
  4. 12
  5. >>> func2('#', 4)
  6. ####
三、默认参数
在默认值的参数不能出现在没有默认值的参数之前。
例子中,只提供一个值,该值赋值给name, age使用默认值: 如何提供了两个值,第二个值将会赋值给age
  1. >>> def func3(name, age = 7): print '%s: %d' % (name, age)
  2. ...
  3. >>> func3('tom')
  4. tom: 7
  5. >>> func3('tom', 8)
  6. tom: 8
例2:如何提供了多个默认值,那么在调用函数的时候,值依次传入给每个参数。如果想跳过对某一个默认参数的赋值,直接为下一个参数赋值,那么要写明到底是把值赋值给哪个参数
  1. >>> def hosts(name, port): print '%s listen on %s' % (name, port)
  2. ...
  3. >>> hosts('http', 80)
  4. http listen on 80
  5. >>> hosts(80, 'http')
  6. 80 listen on http
  7. >>> hosts(port = 80, name = 'http')
  8. http listen on 80
四、参数个数未知的函数定义
  1. >>> def func5(*args):
  2. ... for i in args:
  3. ... print i
  4. ...
  5. >>> func5()
  6. >>> func5('abcd')
  7. abcd
  8. >>> func5('abcd', 'efg', 7)
  9. abcd
  10. efg
  11. 7
五、使用字典接收参数
  1. >>> def func6(**kwargs):
  2. ... for i in kwargs:
  3. ... print '%s: %s' % (i, kwargs[i])
  4. ...
  5. >>> func6()
  6. >>> func6(name = 'bob', age = 10)
  7. age: 10
  8. name: bob
六、元组、字典结合使用       注意:在使用的时候,需把元组放在前面,字典放在后面
  1. >>> def func7(*a, **b):
  2. ... for i in a:
  3. ... print i
  4. ... for m, n in enumerate(b):
  5. ... print '%s: %s' % (m, n)
  6. ...
  7. >>> func7('hello', 'tom', host = 'servera', port = 80)
  8. hello
  9. tom
  10. 0: host
  11. 1: port
综合练习
  1. #!/usr/bin/env python
  2. from operator import add, sub
  3. from random import randint, choice
  4. ops = {'+': add, '-': sub}
  5. maxtries = 2
  6. def doprob():
  7. op = choice('+-')
  8. nums = [randint(1,10) for i in range(2)]
  9. nums.sort(reverse = True)
  10. ans = ops[op](*nums)
  11. pr = '%d %s %d = ' % (nums[0], op, nums[1])
  12. oops = 0
  13. while True:
  14. try:
  15. if int(raw_input(pr)) == ans:
  16. print 'correct'
  17. break
  18. if oops == maxtries:
  19. print 'answer\n%s%d' % (pr, ans)
  20. break
  21. else:
  22. print 'incorrect... try again'
  23. oops += 1
  24. except (KeyboardInterrupt, EOFError, ValueError):
  25. print 'invalid input... try again'
  26. def main():
  27. while True:
  28. doprob()
  29. try:
  30. opt = raw_input('Again? [y]').lower()
  31. if opt and opt[0] == 'n':
  32. break
  33. except (KeyboardInterrupt, EOFError):
  34. break
  35. if __name__ == '__main__':
  36. main()
八、变量的作用域
  1. #!/usr/bin/env python
  2. x = 10
  3. def foo():
  4. print x
  5. foo()

  1. #!/usr/bin/env python
  2. x = 10
  3. def foo():
  4. x = 5
  5. print 'x=', x
  6. foo()
以上程序执行,打印出来的x值是5。如果函数内有一个和全局同名的变量,那么函数内的变量将会覆盖全局变量

九、global语句
  1. #!/usr/bin/env python
  2. x = 10
  3. def foo():
  4. x = 5
  5. print 'x=', x
  6. foo()
  7. print x
最终打印出来x的值仍然是10。如果需要真正的在函数内部将全部变量的值修改。那么执行以下程序:
  1. #!/usr/bin/env python
  2. x = 10
  3. def foo():
  4. global x
  5. x = 5
  6. foo()
  7. print x
程序执行时,打印出来x的值是5
十、lambda匿名函数
  1. #!/usr/bin/env python
  2. def a(x, y):
  3. return x + y
  4. print a(3, 4
可以使用lamdba简化为:
  1. #!/usr/bin/env python
  2. a = lambda x, y: x + y
  3. print a(3, 4)
过滤一个列表,只把奇数留下来: 
  1. #!/usr/bin/env python
  2. alist = [23, 33, 22, 433, 55, 44]
  3. def func1(num):
  4. if num % 2 == 1:
  5. return True
  6. else:
  7. return False
  8. blist = filter(func1, alist)
  9. print blist
使用lambda替换:
  1. #!/usr/bin/env python
  2. alist = [23, 33, 22, 433, 55, 44]
  3. blist = filter(lambda num: num % 2, alist)
  4. print blist

对一个列表实现累加,返回最好终结果:
  1. #!/usr/bin/env python
  2. alist = [1, 44, 2, 55]
  3. def add(x, y):
  4. return x + y
  5. result =reduce(add, alist)
  6. print result
使用lamdba实现:
  1. #!/usr/bin/env python
  2. alist = [1, 44, 2, 55]
  3. result = reduce(lambda x, y : x + y, alist)
  4. print result





posted @ 2016-12-19 14:26  Final233  阅读(179)  评论(0编辑  收藏  举报