MiddleCodeOccasionalNot answered yet
What does this function raise, and why?
Predict what running f() does.
x = 10
def f():
print(x) # (1)
x = 20 # (2)
f()
Determine the output and explain.
UnboundLocalError: local variable 'x' referenced before assignment. Because x is assigned anywhere in the function (line 2), Python treats it as local for the entire function, so the read on line 1 fails. Fix: add global x, or don't shadow it. This is the LEGB scoping rule.
- ✗Thinking name binding is decided at the point of use rather than for the whole function
- ✗Expecting line 1 to read the global
x - ✗Confusing UnboundLocalError with a plain NameError
- →How do
globalandnonlocalchange which scope an assignment targets? - →What are the four scopes in Python's LEGB lookup order?