Skip to content

15. Counter with a Closure

Difficulty: Easy · Topic: Functions & decorators

Write make_counter(start=0, step=1). It returns a function; each call of that function returns the next number: start on the first call, then start + step, and so on.

Every counter is independent: two counters made by make_counter never affect each other. Do not use global variables.

Your code runs in CPython on our servers against 4 tests, including hidden ones.

Sample test

c = make_counter()
[c(), c(), c()]

Expected: [0, 1, 2]

Hints

Hint 1A function defined inside another can read the outer function's variables: that is a closure.
Hint 2To assign to an outer variable, declare it nonlocal first.
Hint 3Return the current value, then advance it.

Learn the concepts

More Python problems

All Python problems