在python函数中使用全局变量

时间:2016-11-18 11:05:26

标签: python

所以这里是在函数中使用x的代码。

x = 1
def f():
    y = x
    x = 2
    return x + y
print x
print f()
print x

但是python不会从函数范围中查找变量,而是导致UnboundLocalError: local variable 'x' referenced before assignment。我不是要修改全局变量的值,我只想在y=x时使用它。

另一方面,如果我只是在返回陈述中使用它,它会按预期工作:

x = 1
def f():
  return x
print x
print f()

有人可以解释原因吗?

1 个答案:

答案 0 :(得分:2)

如果要修改值,必须在函数中指定global x, 但是,仅仅读取值并不是强制性的:

x = 1
def f():
    global x
    y = x
    x = 2
    return x + y
print x
print f()
print x

输出

1
3
2