Problem solving · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Predict the Output - Python Scoping
mediumcode-reading
Problem
Read the program below. For each numbered part, say what is printed or which exception is raised, and state the scoping rule responsible. Do this before running it.
x = "module"
def outer(): # part 1
x = "outer"
def show():
print("show:", x)
x = "rebound"
show()
def bump(): # part 2
total = 0
def add(n):
total += n
add(5)
return total
def make_names(): # part 3
class Config:
prefix = "svc-"
names = [prefix + str(i) for i in range(2)]
return Config.names
def leak(): # part 4
for i in range(3):
pass
squares = [j * j for j in range(3)]
return i, "j" in dir()
outer()
try:
print("bump:", bump())
except Exception as e:
print("bump:", type(e).__name__)
try:
print("names:", make_names())
except Exception as e:
print("names:", type(e).__name__)
print("leak:", leak())Examples
The program prints:
show: rebound
bump: UnboundLocalError
names: NameError
leak: (2, False)- Part 1 prints
rebound, notouter: the inner function reads the variable at call time. - Part 2 raises before
addever readstotal: the assignment makestotallocal toaddfor the whole function body. - Part 3 raises
NameErrorforprefix: a class body is not an enclosing scope for the comprehension. - Part 4 returns
(2, False): aforloop variable leaks into the function scope, a comprehension variable does not.
Hints
- Python decides whether a name is local to a function at compile time by scanning the whole body for assignments. What does that imply for a name that is assigned on line 3 but read on line 2?
- Closures capture variables, not values. When
show()runs, which binding ofxdoes it see? - The rule is LEGB: Local, Enclosing function, Global, Builtins. Where does a class body fit? (It does not.)
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.