使用关键字def定义函数
In [19]: def fib(n): ....: a, b = 0, 1 ....: while a < n: ....: print a, ....: a, b = b, a+b ....: In [20]: fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
函数可以直接传递给变量,相当于重新命名函数名:
In [21]: fib Out[21]: <function __main__.fib> In [22]: f = fib In [23]: f(100) 0 1 1 2 3 5 8 13 21 34 55 89
函数一般都有返回值,如果没有返回值,那么默认返回值是none
In [24]: def fib2(n): ....: result = [] ....: a,b=0,1 ....: while a<n: ....: result.append(a) ....: a,b=b,a+b ....: return result ....: In [25]: fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 In [26]: fib2(100) Out[26]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
本文出自 “平凡之路” 博客,请务必保留此出处http://linjohn.blog.51cto.com/1026193/1609719
原文地址:http://linjohn.blog.51cto.com/1026193/1609719