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) # 5Each call to make_adder creates a new n, so closures from separate calls do not interfere.
Changing a captured variable
Reading works automatically. Assigning would make a new local variable, so declare the name with nonlocal first:
def counter():
count = 0
def tick():
nonlocal count
count += 1
return count
return tickClosures give you small pieces of private state without a class. Reach for a class when you need several methods or want other code to inspect that state.
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.
The explanation opens here once every check passes.