Skip to main content
Python & FastAPI Interviews Predict Output P0 Medium

LEGB scope and UnboundLocalError

Predict whether this prints 10 or raises an error, and explain why Python decides at compile time.

Official Reference

Code Snippet

count = 10
def bump():
    try:
        print(count)
        count += 1
    except Exception as e:
        print(type(e).__name__)
bump()

Expected Output & Explanation

UnboundLocalError

Because count += 1 assigns to count inside bump(), Python compiles count as a local variable for the entire function body. Reading count on the line before it is assigned raises UnboundLocalError instead of falling back to global.

Follow-up Interview Question · When is nonlocal needed instead of global?

Module Context & References

Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.