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 = 0​
3 def inc():​
4 nonlocal count​
5 count += 1​
6 return count​
7 return inc​
8​
9c = make_counter()​
10print(c(), c(), c()) # 1 2 3​

Try 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.