Practice Question: Scope of Variables

What is the output of the following code snippet?

Python
x = 1

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

func()
Answer
Plain text
UnboundLocalError: local variable 'x' referenced before assignment

Explanation:

First, the Python interpreter compiles the whole function body and sees the assignment x = 2 inside func. Because of this assignment, it decides that x is a local variable throughout the entire function.

That means that when the interpreter reaches print(x), it is not looking at the global x = 1, but at the local x inside func. However, this local x has not been assigned a value yet (the assignment comes after the print), so when the code runs, Python raises:

Plain text
UnboundLocalError: local variable 'x' referenced before assignment
Back to collection