So I was writing some conditionals when I started facing this issue. Can someone please explain to me why this code fails to execute? (I simplified the semantics to make it simpler to reproduce)
a = 1
b = 2
def run():
if a < b:
a = b
run()
It raises an UnboundLocalError: local variable 'a' referenced before assignment
. It seems to happen to the variable being assigned inside the if block so I changed the function to this:
def run():
if a < b:
b = a
And then the message was UnboundLocalError: local variable 'b' referenced before assignment
.
I am not sure if this is due to scoping but this code works normally:
def run():
print(a)
print(b)
Is there any think I missed from how Python works? If so, sorry for the dumb question but I have been working with Python for more than 4 years and never saw this before.
Tested in Python 2.7.15rc1
inside WSL and Python 3.6.4
in Windows.