Search code examples
pythonglobal-variablesinterpreter

Printing the value of a global variable and then changing the value in python


The global keyword is used in a function to refer to a global variable within that function and modify it. However even if the global keyword is not used and if we just try to print the variable, python assumes it is the global variable that is being referred and simply prints that like so.

a = 2
def foo():
    print(a)
foo()

the above code outputs 2. But the following code throws an error.

a = 2
def foo():
    print(a)
    a = 3
foo()

I get an UnboundLocalError saying local variable 'a' was referenced before assignment. Now since python is an interpreted language and execution happens one line at a time, shouldn't it first print the global value of a which is 2 (like in the first case) and then create a local variable with the same name ans assign it to 3. In the second case how does the interpreter know right at the print statement that I am referring to another variable 'a' in the next line? Why doesn't it behave in the same way as above?

PS: I do understand that using the global keyword can help me change the value of a from 2 to 3.


Solution

  • Python byte code is interpreted; Python source is first compiled to byte code.

    Names are either local or global within a single scope, and that determination is made at compile time; you can't switch half way through a fuction. If there is any assignment to a in the function, it is local everywhere in the function unless you use global a.

    a = 2
    def foo():
        global a
        print(a)
        a = 3
    

    Without the global statement, print(a) refers to the local name a, even though it occurs before the actual assignment.