Python · Level 3 Functions

Closures

A function defined inside another one remembers the variables around it — the foundation of decorators and callbacks.

  • Functions returning functions
  • Captured variables
  • nonlocal to update them

An inner function keeps access to the outer function's variables even after the outer function has returned. Use nonlocal to change them.

def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}!"
    return greet

hello = make_greeter("Hello")
hello("Ana")   # 'Hello, Ana!'  — greeting was remembered

Write make_counter(start=0, step=1) that returns a function. Each call to that function adds step to the count and returns the new value. Every counter keeps its own count.

solution.py
Test Suites Pending
Stdout