Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 13

Write a function that demonstrates nonlocal usage

Medium

14 minute session

Summary

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

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

Explanation

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)

Explanation

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 input 0

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

Sample output 0

(1, 2)

Explanation 0

Two calls on the same counter produce 1 then 2.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:04 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.