理解局部变量和全局变量
def func(x):
print 'X in the beginning of func(x): ', x
x = 2
print 'X in the end of func(x): ', x
x = 50
func(x)
print 'X after calling func(x): ', x
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 50
变量 x 在函数内部被重新赋值。但在调用了函数之后,x 的值仍然是50。为什么?
在函数 func 外部,定义的变量 x,赋值为 50,作为参数传给了函数 func。而在函数 func 内部,变量 x 是形参,它的作用域是整个函数体内部。它与外面的那个 x 没有关系。只不过它的初始值是由外面那个 x 传递过来的。 所以,虽然函数体内部的 x 被重新赋值为 2,也不会影响外面那个 x 的值。 不过有时候,我们希望能够在函数内部去改变一些变量的值,并且这些变量在函数外部同样被使用到。怎么办?
使用return返回
return x x=func(x)
使用全局变量
def func():
global x
print 'X in the beginning of func(x): ', x
x = 2
print 'X in the end of func(x): ', x
x = 50
func()
print 'X after calling func(x): ', x
输出:
X in the beginning of func(x): 50
X in the end of func(x): 2
X after calling func(x): 2
函数 func 不再提供参数调用。而是通过 global x 告诉程序:这个 x 是一个全局变量。于是函数中的 x 和外部的 x 就成为了同一个变量。这一次,当 x 在函数 func 内部被重新赋值后,外部的 x 也随之改变。