python
def outer():
x = 10
def inner():
print(x)
x += 1
inner()
outer()
Answer:
UnboundLocalError: local variable 'x' referenced before assignmentThis one surprises a lot of people - it does NOT print
10. Here's why: because inner() assigns to x (x += 1), Python treats x as a LOCAL variable throughout the entire function the moment it sees any assignment to it, even before that line executes. So the print(x) line is trying to read a local x that hasn't been assigned yet.Fixed version:
python
def outer():
x = 10
def inner():
nonlocal x
print(x)
x += 1
inner()
The
nonlocal keyword tells Python "this x refers to the enclosing function's variable, not a new local one."This is a genuinely tricky one - Python decides variable scope at compile time based on whether a name is assigned anywhere in the function, not based on execution order. Great interview question for testing real understanding of closures vs. just pattern-matching syntax.