0

I am a bit confused by how Python handles variable scope.

Below is a simple example that I created to explain the varialbe scope. When I execute the code below, the reference error surprisingly happens at the line print(x) instead of x = x + 1.

def foo():
    print(x)
    x = x + 1

x = 0
foo()

I would assume at the line print(x), Python should have access to the x in the global scope, no? (In fact, if we comment out the line x = x + 1, the code actually runs)

How exactly does the Python intepreter work here?

TimC
  • 305
  • 1
  • 3
  • 9
  • If a variable is assigned to inside a function, then it is local to that function unless declared as `global`. It makes no difference whether the attempted read-only access to the variable is before or after the assignment statement. – alani Sep 29 '20 at 09:10
  • @alani hmm, does that Python interpreter will parse the whole function before executing it? – TimC Oct 01 '20 at 03:52
  • Yes, the CPython interpreter runs byte code, not source code. Byte code is derived from compiling entire code blocks. – MisterMiyagi Oct 01 '20 at 05:34

0 Answers0