I only just came across this and it's managed to confuse me. I tried to use the same idea as Function2 but it didn't work, what confused me was it was managing to access other global variables even though I hadn't used global at all.
It seems it depends on how you use the variable which just doesn't seem right to me.
I understand all I need to do is global number in Function2 but why is it that this doesn't work?
number = 5
def Function1():
temp = number
print(temp)
def Function2():
number += 1
print(number)
def Function3():
print(number)
Function1() # >>> 5
Function2() # line 8, in Function2
# number += 1
# UnboundLocalError: local variable 'number' referenced before assignment
Function3() # >>> 5
Function1 and Function3 work as I expect whereas Function2 does not.
I also tried replacing the number += 1 with number = number + 1 but same error occured.
- Python version 3.9.13