Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Understanding the Nonlocal Keyword in Python
๐ Scenario: Imagine you are creating a simple counter inside a function. You want to increase the count each time you call a nested function. This project will help you learn how to use the nonlocal keyword to change a variable in the outer function from inside the inner function.
๐ฏ Goal: You will build a function with a nested function that increases a counter using the nonlocal keyword. You will then print the updated count.
๐ What You'll Learn
Create a function with a nested function
Use the nonlocal keyword to modify the outer variable
Call the nested function to increase the counter
Print the final counter value
๐ก Why This Matters
๐ Real World
Using <code>nonlocal</code> helps when you want to keep track of changes inside nested functions without using global variables. This is useful in creating counters, stateful functions, or closures.
๐ผ Career
Understanding <code>nonlocal</code> is important for writing clean, maintainable Python code, especially when working with nested functions, decorators, or advanced function designs.
Progress0 / 4 steps
1
Create the outer function with a counter variable
Create a function called counter that has a variable count set to 0 inside it.
Python
Hint
Define a function with def counter(): and inside it write count = 0.
2
Add a nested function that uses nonlocal to change count
Inside the counter function, create a nested function called increase. Use the nonlocal keyword for count inside increase. Then add 1 to count inside increase.
Python
Hint
Inside counter, define def increase():. Use nonlocal count to tell Python you want to change the outer count. Then write count += 1.
3
Call the nested function and return the count
Still inside counter, call the nested function increase() once. Then return the value of count from counter.
Python
Hint
Call increase() inside counter to add 1 to count. Then use return count to send the updated count back.
4
Print the result of calling counter
Call the function counter() and print its result using print(counter()).
Python
Hint
Use print(counter()) to show the number 1, which is the updated count.
Practice
(1/5)
1. What does the nonlocal keyword do in Python?
easy
A. Declares a variable as global across all modules.
B. Allows an inner function to modify a variable from its outer function.
C. Creates a new local variable inside the inner function.
D. Prevents any changes to variables in the outer function.
Solution
Step 1: Understand variable scopes
Variables inside a function are local by default, and inner functions cannot change outer variables unless specified.
Step 2: Role of nonlocal
The nonlocal keyword allows the inner function to access and modify variables from the nearest enclosing function scope.
Final Answer:
Allows an inner function to modify a variable from its outer function. -> Option B
Inside increment(), count = count + 1 tries to read and write count. Without nonlocal, Python treats count as local, but it is used before assignment.
Step 2: Fix with nonlocal
Adding nonlocal count tells Python to use the count from counter(), allowing modification.
Final Answer:
Missing 'nonlocal count' inside increment() -> Option C
Quick Check:
Modify outer variable needs nonlocal = A [OK]
Hint: Add nonlocal before modifying outer variable inside inner function [OK]
Common Mistakes:
Using global instead of nonlocal
Ignoring variable scope causing UnboundLocalError
Returning count without incrementing properly
5. Consider this code:
def make_accumulator():
total = 0
def add(value):
nonlocal total
total += value
return total
return add
acc = make_accumulator()
print(acc(5))
print(acc(3))
print(acc(-2))
What is the output of this code?
hard
A. 5\n8\n6
B. 5\n3\n-2
C. 0\n5\n8
D. Error: nonlocal used incorrectly
Solution
Step 1: Understand closure with nonlocal
The function make_accumulator() returns add, which remembers total. The nonlocal total lets add update total each call.
Step 2: Trace calls to acc
First call: total=0+5=5, prints 5. Second call: total=5+3=8, prints 8. Third call: total=8+(-2)=6, prints 6.
Final Answer:
5
8
6 -> Option A
Quick Check:
Accumulator sums values using nonlocal total = B [OK]
Hint: nonlocal keeps state in nested function closures [OK]
Common Mistakes:
Expecting total to reset each call
Confusing nonlocal with global
Thinking output is separate values, not cumulative