您的位置:首页 > 编程语言 > Python开发

[python]global全局变量

2017-07-25 20:28 387 查看
在函数的内部如果想使用函数外的变量,并且希望改变该变量的值,可以考虑使用global关键字,从而告诉解释器该变量在函数体外部定义,当前函数可以对其进行改变。

下面请看加global语句和不加global语句使用变量的差别。

不加global

#!/usr/bin/Python
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x


输出为:

x is 50
Changed local x to 2
x is still 50


加global

#!/usr/bin/python
def func():
global x

print 'x is', x
x = 2
print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x


输出为:

x is 50
Changed local x to 2
Value of x is 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python global