What happens?
x = 10
def f():
print(x)
x = 5
f()Options
- Prints 10
- Prints 5
- UnboundLocalError (Correct option)
- 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.