L3·Functions & Modules
🔒Scope & Closures
LEGB rule and functions that capture state.
scopeclosurenonlocalglobal
§ 1LEGB
Name lookup order: Local → Enclosing → Global → Built-in.
§ 2global vs nonlocal
global rebinds a module-level name. nonlocal rebinds the nearest enclosing function's name.
§ 3Closures
A nested function that remembers variables from its enclosing scope, even after that scope returns.
Worked example
1def make_counter():2 count = 03 def inc():4 nonlocal count5 count += 16 return count7 return inc89c = make_counter()10print(c(), c(), c()) # 1 2 3Try it live · Python runs in your browser
Loading playground…
Checkpoint quiz
Question 1 / 2
Without 'nonlocal', assigning to 'count' inside inc would:
Lesson test
Take an 8-question test on “Scope & Closures” — concepts, output prediction, bug spotting and interview questions.