在python函数中使用全局变量
问题描述:
所以这里是在函数内部使用x
的代码。在python函数中使用全局变量
x = 1
def f():
y = x
x = 2
return x + y
print x
print f()
print x
但蟒是不会来查找变量out功能范围,并导致UnboundLocalError: local variable 'x' referenced before assignment
。我不想修改全局变量的值,我只是想在我做y=x
时使用它。
在另一方面,如果我只是在回报statment使用它,它按预期工作:
x = 1
def f():
return x
print x
print f()
有人能解释为什么吗?
答
你在你的函数来指定global x
如果你想修改你的价值, 但它不是强制性的,光看数值:
x = 1
def f():
global x
y = x
x = 2
return x + y
print x
print f()
print x
输出
1
3
2
问题不回答'y = x'但是'y = x'与'x = 2'一起。删除其中一个,并且此错误消失。 (但你可能会有所不同:)) – furas
但是'x = 2'低于'y = x',所以我的意思是python应该首先处理'y = x',将y赋值给y,然后在'x = 2'创建一个新的局部变量并为其赋值2。不是吗? –