[英]Global variable exists still I get "UnboundLocalError: local variable 'a' referenced before assignment"
The following python code gives an error.以下 python 代码给出了一个错误。 Why isn't it referencing the global variable a?
为什么不引用全局变量a?
a = 10
def b(x):
if(x == True):
a = 2
return a
print(b(False))
The error:错误:
Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 6, in b
UnboundLocalError: local variable 'a' referenced before assignment
>
The issue is that you're using a local variable that has the same name of the global one.问题是您使用的局部变量与全局变量同名。 This can help: Modifying global variable with same name as local variable
这可以帮助: Modifying global variable with same name as local variable
Edit: in fact, this seems to be working:编辑:事实上,这似乎有效:
a = 10
def b(x):
if(x == True):
globals()['a'] = 2
return a
print(b(False))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.