0
a=1

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

func()

The code above issues the following error:

local variable 'a' referenced before assignment

Given the imperative nature of Python i expect that the variable a is treated like a global variable before the Interpreter reaches the next line, where the variable a is assigned again but as a local variable (since it happens inside the function).

chakmeshma
  • 246
  • 8
  • 27
  • 2
    This should answer your question: [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – mkrieger1 Nov 06 '21 at 15:58
  • 2
    Python source code is not interpreted; Python *byte* code is, and you get the byte code by *compiling* the source code. During compilation, the code generator needs to know if `a` is local or not, and that decision is made once for the entire scope: it cannot change from line to line. – chepner Nov 06 '21 at 15:59
  • https://www.w3schools.com/python/python_variables_global.asp says "Variables that are created outside of a function are known as global variables." – chakmeshma Nov 06 '21 at 16:00
  • That's a gross oversimplification. – chepner Nov 06 '21 at 16:01
  • 1
    It's the way the language handles locals vs. globals. If you declare `global a` within the function, then all references to `a` within the function refer to the global. If you don't declare `global a`, but don't assign to `a` within the function, then all references again refer to the global. But if you don't declare `global a`, and you do assign to `a` within the function, then all references to `a` within the function refer to the local variable. In this case, if you try to access its value before assigning to it, you will get an error. – Tom Karzes Nov 06 '21 at 16:02

0 Answers0