In Python, the following code works:
a = 1
b = 2
def test():
print a, b
test()
And the following code works:
a = 1
b = 2
def test():
if a == 1:
b = 3
print a, b
test()
But the following does not work:
a = 1
b = 2
def test():
if a == 1:
a = 3
print a, b
test()
The result of this last block is an UnboundLocalError message, saying a is referenced before assignment.
I understand I can make the last block work if I add global a in the test() definition, so it knows which a I am talking about.
Why do I not get an error when assigning a new value to b?
Am I creating a local b variable, and it doesn't yell at me because I'm not trying to reference it before assignment?
But if that's the case, why can I print a, b in the case of the first block, without having to declare global a, b beforehand?