I'm trying to understand why the following code fails, not recognizing the global variable:
xy = 4
def b():
print(xy)
if xy is None:
xy = 2
def a():
print(xy)
b()
a()
When running, I get the output:
$ 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
Why global xy is not recognized in function b?
Removing the if clause in function b makes the error go away.
Thanks.