0

I am curious about how Python interpreter handles function.

The code below will generate an error at the line print(x).

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

x = 0
foo()

I would assume that if we expand the code, it will be something like below

x = 0
print(x)
x = 1

I understand the variable scope in Python.

But my real question is, at the line print(x), shouldn't the Python interpreter have no knowledge about the later variable declaration and simply reference the x in the global scope?

TimC
  • 305
  • 1
  • 3
  • 9
  • 1
    "shouldn't the Python interpreter have no knowledge about the later variable declaration and simply reference the x in the global scope?" No, that is just not correct. – juanpa.arrivillaga Oct 01 '20 at 04:08
  • A variable within a function is local unless declared `global`. – DYZ Oct 01 '20 at 04:08
  • 3
    Whenever you *assign to a variable* in a function, at *compile time*, the variable is marked as local. A variable cannot be both local and global. If you want a variable to be treated as global in a function where it is assigned to, then you need to use a `global` statement. A global statement is not necessary if you simply reference a variable – juanpa.arrivillaga Oct 01 '20 at 04:10

0 Answers0