Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build an Increment Decrement Counter Factory

Create a closure-based counter factory that returns increment, decrement and getter functions sharing the same state.

Python practice14 minClosures & Function FactoriesIntermediateLast updated April 13, 2026

Problem statement

Implement make_counter(start=0, step=1) which returns a tuple (inc, dec, get). inc() increments the shared counter by step and returns the new value. dec() decrements the counter by step and returns the new value. get() returns the current value without modifying it. The counter's state must be captured in a closure (no global variables).

Task

Learn to use closures to encapsulate mutable state and build simple function factories that produce stateful operations.

Examples

Basic usage

Input

inc, dec, get = make_counter(10, 2) inc() get()

Output

12 12

Starting at 10 with step 2, inc() moves the counter to 12 and returns 12; get() returns the current value 12.

Input format

A single call to make_counter(...) and then calling the returned functions. Tests will call the functions returned by make_counter in a single expression.

Output format

The functions inc and dec return integers representing the updated counter; get returns the current integer value.

Constraints

start and step will be integers. You must use a closure to keep the counter state (use of global variables is not allowed). Returned object must be a tuple (inc, dec, get) where each element is a callable.

Samples

Sample 1

Input

make_counter(0, 1)[0]()

Output

1

Counter starts at 0; inc() with step 1 returns 1.