Understanding variable scope and shadowing in Python
This is an easy Python fundamentals question that tests your grasp of scope resolution and variable binding. It's common in screening interviews because scope bugs are frequent in real code, and the question quickly reveals whether a candidate understands Python's name-lookup rules.
To answer correctly, you need to trace through how Python resolves names in different scopes—local, enclosing, global, and built-in (the LEGB rule). Pay special attention to when a variable is first assigned within a function, as this affects whether references to that name resolve to an outer scope or the local one. The question rewards careful reading of the actual code flow rather than assumptions about how it "should" behave.
- Local vs. global scope
- Variable assignment and binding
- Scope shadowing and the LEGB rule
- UnboundLocalError and when it occurs