0

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
hjw
  • 3
  • 1
  • It may not be intuitive, but the `global` keyword is only needed to modify a global variable versus access it. See: https://stackoverflow.com/questions/10360229/python-why-is-global-needed-only-on-assignment-and-not-on-reads – rhurwitz Dec 13 '22 at 18:31
  • You **never** need `global` to *merely access* a global variable, you need `global` to *assign* to a local variable. Any assignment to a variable in a function makes the compiler mark it as *local* by default. Hence, if you try to access that variable before it is defined, you get an UnboundLocal error. This is the same as just doing `x += 1` when `x` has no value (in the global scope, this would raise a NameError) – juanpa.arrivillaga Dec 13 '22 at 18:49

0 Answers0