PythiloLesson 8 of 9 · progress kept in this browser

Functions that return functions

A function defined inside another can read the outer function's variables. When the inner function is returned, it keeps those variables alive. That pairing is a closure.

def make_adder(n):
    def add(x):
        return x + n
    return add

add_two = make_adder(2)
add_two(3)  # 5

Each call to make_adder creates a new n, so closures from separate calls do not interfere.

Your task

Write running_total() returning a function add(n). Each call adds n to a total kept inside the closure and returns the new total. Separate calls to running_total() keep separate totals.

Next: Typing