Problem No 13
Write a function that demonstrates nonlocal usage
Medium≈ 14 minute session
Lesson guide
What this Python exercise practices
Write a function that demonstrates nonlocal usage is a intermediate practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 14 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Intermediate
- Estimated time
- 14 minutes
Practice path
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.
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.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.