0

I am a novice in Python and wondering the situation below.

x = 1
def func():
    print(x)
    x = 2
    return x

So I got the UnboundLocalError: local variable 'x' referenced before assignment. But if I right understand - Python read and execute code row by row. So in first statement inside function "print(x)" it must just relay global variable x which eq. 1, but instead I got the error. Please explain, I think it simple.

  • Do these help?: https://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment, https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use, https://stackoverflow.com/questions/21456739/unboundlocalerror-local-variable-l-referenced-before-assignment-python and https://www.google.com/search?q=unbound+local+variable+error+python – The Amateur Coder May 19 '22 at 16:40
  • and this: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – ZiyadCodes May 19 '22 at 16:42
  • 1
    Does this 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) – The Amateur Coder May 19 '22 at 16:43
  • you have to tell python explicitly that you want `x` inside the function to refer to the global variable – Anentropic May 19 '22 at 16:49
  • 1
    Python is not executed row-by-row; CPython *compiles* all the source in a given module to byte code before executing anything in the byte-code interpreter. Other implementations may not compile anything, but that doesn't affect the semantics. – chepner May 19 '22 at 17:05

1 Answers1

0

I think your problem was explained as well in the FAQ of python docs

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

  • 2
    Is that means that first interpreter’s operation is initializing the scope’s variables? And only after - all row by row operations? – Ruslan Mansurov May 19 '22 at 17:02
  • 2
    *Statements* are executed in order, but decisions about which names are local and which are global are made when the function is *defined*, not when it is executed. – chepner May 19 '22 at 17:06