我试图理解为什么以下代码失败,而不识别全局变量:
xy = 4
def b():
print(xy)
if xy is None:
xy = 2
def a():
print(xy)
b()
a()在运行时,我得到了输出:
$ python3 globals-test2.py
4
Traceback (most recent call last):
File "globals-test2.py", line 12, in <module>
a()
File "globals-test2.py", line 10, in a
b()
File "globals-test2.py", line 4, in b
print(xy)
UnboundLocalError: local variable 'xy' referenced before assignment为什么功能b中不承认全局xy?
删除函数b中的if子句将使错误消失。
谢谢。
发布于 2020-11-05 17:37:50
因为在函数中使用它,所以通过在函数顶部添加global xy来声明它为全局变量。
xy = 4
def b():
global xy
print(xy)
if xy is None:
xy = 2
def a():
print(xy)
b()
a()https://stackoverflow.com/questions/64702379
复制相似问题