a = 10
print(a) # UnboundLocalError raised here
a = 20
UnboundLocalError: local variable 'a' referenced before assignment
According to Python's documentation, the interpreter will first notice an assignment for a variable named
a in the scope of
f() (no matter the position of the assignment in the function) and then as a consequence only recognize the variable
a as a local variable in this scope. This behavior effectively shadows the global variable
The exception is then raised "early", because the interpreter which executes the code "line by line", will encounter the print statement referencing a local variable, which is not yet bound at this point (remember, Python is looking for a
local variable here).
As you mentioned in your question, one has to use the
global keyword to explicitly tell the compiler that the assignment in this scope is done to the global variable the correct code would be:
a = 10 def f(): global a print(1) print(a) # Prints 10 as expected a = 20 f()
As @2rs2ts said in a now-deleted answer, this is easily explained by the fact that "Python is not merely interpreted, it is compiled into a bytecode and not just interpreted line by line".