[python]global全局变量

来源:互联网 发布:加拿大北电网络市值 编辑:程序博客网 时间:2024/05/21 20:27

在函数的内部如果想使用函数外的变量,并且希望改变该变量的值,可以考虑使用global关键字,从而告诉解释器该变量在函数体外部定义,当前函数可以对其进行改变。
下面请看加global语句和不加global语句使用变量的差别。

  • 不加global
 #!/usr/bin/Pythondef func(x):    print 'x is', x    x = 2    print 'Changed local x to', xx = 50func(x)print 'x is still', x

输出为:

x is 50Changed local x to 2x is still 50
  • 加global
 #!/usr/bin/pythondef func():    global x    print 'x is', x    x = 2    print 'Changed local x to', xx = 50func()print 'Value of x is', x

输出为:

x is 50Changed local x to 2Value of x is 2
原创粉丝点击