Repaso
Español
PythonIntermediatePY-35

What happens?

x = 10
def f():
    print(x)
    x = 5

f()

Options

  1. Prints 10
  2. Prints 5
  3. UnboundLocalError (Correct option)
  4. NameError: x is not defined

Answer

UnboundLocalError

Why

Python decides which names are local when it reads the whole function, before running it.

Because x = 5 appears inside f, x is local for the ENTIRE function, even on the line before the assignment.

So print(x) tries to read a local x that has no value yet → UnboundLocalError. Use a different name, or global x if you really mean the outer one.

Remember

Any assignment inside a function makes that name local everywhere in it.

Key terms

Practice this question in Repaso