Python Scope and LEGB Rules Explained
Scope determines where Python looks for a name when it executes your code. In interviews, confusion around scope often produces the wrong answer even when the logic itself is simple. The LEGB rule gives you a consistent mental model for local, enclosing, global, and built-in names.
The LEGB order
Python resolves names in this order: Local, Enclosing, Global, Built-in. That means it checks the current function first, then outer functions, then the module level, and finally built-in names like len or print.
x = 10
def outer():
x = 20
def inner():
print(x)
inner()
outer()The output is 20 because the inner function uses the enclosing scope from outer, not the global x. This is one of the most common interview traps because many learners assume Python will always reach for the global value.
How to trace scope correctly
When you dry run a snippet, write down which frame each name belongs to before you execute it. Ask yourself whether the name is created inside a function, referenced from an outer function, or imported from the module level. That habit makes scope questions much easier to solve under pressure.
Continue learning
The Complete Guide to Tracing Python Code (With Examples)
Learn how to build trace tables, predict stdout, and pass Python dry-run interview questions.
10 Python Output Questions for Interview Preparation
Ten classic Python output patterns that appear on technical phone screens, with tracing tips.
How to Dry Run Python Code: Step-by-Step Method
A repeatable five-step method for predicting Python program output under interview pressure.