Scope and Closures
LockedLesson 11 of 60 · Syntax · Medium
Finish these first:Functions →Or pass the tests below to unlock it now.
The big idea
Name lookup follows LEGB: Local, Enclosing, Global, Built-in. A closure captures variables from its enclosing scope.
Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Read the lesson
Name lookup follows LEGB: Local, Enclosing, Global, Built-in. A closure captures variables from its enclosing scope.
def counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
Late binding gotcha: closures capture the variable, not its value at definition time.
Quick check
Before writing code: What should `(lambda c: (c(), c(), c()))(make_counter())` return when your implementation of Scope and Closures is working?
Your challenge
Write make_counter() returning a function that returns 1, 2, 3, ... on successive calls.
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
See how Python compares side-by-side with Java.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Scope and Closures.
Learn this first
- FunctionsNot yet