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, not outer: the inner function reads the variable at call time.
  • Part 2 raises before add ever reads total: the assignment makes total local to add for the whole function body.
  • Part 3 raises NameError for prefix: a class body is not an enclosing scope for the comprehension.
  • Part 4 returns (2, False): a for loop variable leaks into the function scope, a comprehension variable does not.

Hints

  1. 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?
  2. Closures capture variables, not values. When show() runs, which binding of x does it see?
  3. The rule is LEGB: Local, Enclosing function, Global, Builtins. Where does a class body fit? (It does not.)

Last reviewed 8 September 2026