Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Write a function that demonstrates nonlocal usage

Learn how to use the nonlocal keyword by creating a closure that keeps internal state across calls.

Python practice14 minFunctions & ScopeIntermediateLast updated March 17, 2026

Problem statement

Write a function create_counter() that returns another function (a counter). Each time the returned counter function is called, it should increment an internal count and return the new value. Use the nonlocal keyword to modify the count from inside the nested function. The first call to a fresh counter should return 1.

Task

Implement create_counter() that returns a function using a nonlocal variable to track and increment a counter each time the returned function is called.

Examples

Single call on a new counter

Input

create_counter()()

Output

1

create_counter() returns a new counter function. Calling it once increments the internal count from 0 to 1 and returns 1.

Multiple calls on the same counter

Input

(lambda c: (c(), c(), c()))(create_counter())

Output

(1, 2, 3)

The lambda creates one counter, calls it three times in sequence, and returns the tuple of results showing the nonlocal state incrementing.

Input format

Each test calls the functions directly as expressions, e.g., create_counter()(), or uses a temporary variable via a lambda to call multiple times.

Output format

Return values from the evaluated expression. For example "1" or a tuple representation like "(1, 2)".

Constraints

- Use nonlocal to modify the enclosed count variable. - The returned counter must start counting at 1 on its first call. - Do not use global variables. - The counter should be independent per create_counter() call.

Samples

Sample 1

Input

(lambda c: (c(), c()))(create_counter())

Output

(1, 2)

Two calls on the same counter produce 1 then 2.