×

python · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a function that remembers where it was made.

You can define an inside another one and return it. The inner function can read the outer function's variables, even after the outer one has finished. A function that carries its surroundings with it like this is a closure.

Each call to the outer function makes a brand new closure with its own memory, so two counters never share a count.

To change a remembered variable, not only read it, the inner function must say first. Without that line, Python treats count as a brand new variable of its own.

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count = count + 1
        return count
    return counter

tickets = make_counter()
queue = make_counter()
print(tickets(), tickets(), tickets())
print(queue())

Closures are how the decorators in the next lesson remember the function they wrap.