python:Python2.7里如何定义函数

使用关键字def定义函数

In [19]: def fib(n):
   ....:     a, b = 0, 1
   ....:     while a < n:
   ....:         print a,
   ....:         a, b = b, a+b
   ....:
In &#91;20&#93;: fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
 &#91;/code&#93;
    函数可以直接传递给变量,相当于重新命名函数名:
 &#91;code&#93;
In &#91;21&#93;: fib
Out&#91;21&#93;: <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

You might also like:

Sidebar