GCGrowCarrer

Scope and Closures

Locked

Lesson 11 of 60 · Syntax · Medium

Finish these first:Functions →Or pass the tests below to unlock it now.

1

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.
Key words (tap to learn):
2

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.

3

Quick check

Before writing code: What should `(lambda c: (c(), c(), c()))(make_counter())` return when your implementation of Scope and Closures is working?

4

Your challenge

2 sample tests, 1 hidden

Write make_counter() returning a function that returns 1, 2, 3, ... on successive calls.

Stuck? Get a hint (free)
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.

Mastery0%

Learn this first

Opens up next