PDF版 ePub版

# 函数(2)

## 返回值

#!/usr/bin/env Python
# coding=utf-8

def fibs(n):
result = [0,1]
for i in range(n-2):
result.append(result[-2] + result[-1])
return result

if __name__ == "__main__":
lst = fibs(10)
print lst

\$ python 20202.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

>>> def my_fun():
...     return 1,2,3
...
>>> a = my_fun()
>>> a
(1, 2, 3)

>>> def my_fun():
...     print "I am doing somthin."
... 

>>> a = my_fun()
I am doing somthin.

>>> print a
None

>>> my_fun()
I am doing somthin.

>>> def my_fun():
...     print "I am coding."
...     return
...     print "I finished."
...
>>> my_fun()
I am coding.

## 函数中的文档

“程序在大多数情况下是给人看的，只是偶尔被机器执行以下。”所以，写程序必须要写注释。前面已经有过说明，如果用 # 开始，Python 就不执行那句（Python 看不到它，但是人能看到），它就作为注释存在。

#!/usr/bin/env python
# coding=utf-8

def fibs(n):
"""
This is a Fibonacci sequence.
"""
result = [0,1]
for i in range(n-2):
result.append(result[-2] + result[-1])
return result

if __name__ == "__main__":
lst = fibs(10)
print lst

>>> def my_fun():
...     """
...     This is my function.
...     """
...     print "I am a craft."
...
>>> my_fun.__doc__
'\n    This is my function.\n    '

Help on function my_fun in module __main__:

my_fun()
This is my function.

## 参数和变量

### 比较参数和变量

>>> def add(x):     #x 是参数，准确说是形参
...     a = 10      #a 是变量
...     return a+x  #x 就是那个形参作为变量，其本质是要传递赋给这个函数的值
...
>>> x = 3           #x 是变量，只不过在函数之外
>>> add(x)          #这里的 x 是参数，但是它由前面的变量 x 传递对象 3
13
13

## 全局变量和局部变量

x = 2

def funcx():
x = 9
print "this x is in the funcx:-->",x

funcx()
print "--------------------------"
print "this x is out of funcx:-->",x

this x is in the funcx:--> 9
--------------------------
this x is out of funcx:--> 2

x = 2
def funcx():
global x    #跟上面函数的不同之处
x = 9
print "this x is in the funcx:-->",x

funcx()
print "--------------------------"
print "this x is out of funcx:-->",x

this x is in the funcx:--> 9
--------------------------
this x is out of funcx:--> 9

## 命名空间

>>> x = 7
>>> scope = vars()
>>> scope['x']
7
>>> scope['x'] += 1
>>> x
8
>>> scope['x']
8