The nonlocal keyword lets you change a variable in an outer function from inside a nested function. It helps when you want to keep track of changes without using global variables.
Nonlocal keyword in Python
Start learning this pattern below
Jump into concepts and practice - no test required
def outer_function(): variable = None def inner_function(): nonlocal variable variable = 'new_value' inner_function()
You must declare nonlocal before changing the variable inside the inner function.
The variable must exist in the nearest outer function scope, not global or local to inner function.
nonlocal lets the inner function update count from the outer function.def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment count_up = counter() print(count_up()) # 1 print(count_up()) # 2
message variable from the outer function using nonlocal.def greet(): message = 'Hello' def change_message(): nonlocal message message = 'Hi' change_message() print(message) greet() # Output: Hi
This program uses nonlocal to increase factor each time the inner function runs, changing the multiplication result.
def make_multiplier(): factor = 2 def multiply(number): nonlocal factor factor += 1 return number * factor return multiply multiplier = make_multiplier() print(multiplier(5)) # First call print(multiplier(5)) # Second call
If you forget nonlocal, Python treats the variable as local and you get an error if you try to assign it.
nonlocal only works with variables in the nearest outer function, not global variables.
nonlocal lets inner functions change variables from outer functions.
It helps keep track of changing data without using global variables.
Always declare nonlocal before assigning to the variable inside the inner function.
Practice
nonlocal keyword do in Python?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
Thenonlocalnonlocalkeyword 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 BQuick Check:
nonlocal changes outer function variable = A [OK]
- Confusing nonlocal with global keyword
- Thinking nonlocal creates new variables
- Assuming nonlocal works outside functions
nonlocal inside a nested function?Solution
Step 1: Recall the syntax for nonlocal
The keywordnonlocalis followed by the variable name to indicate it refers to an outer function's variable.Step 2: Compare options
Only nonlocal variable_name uses the correct keyword and syntax:nonlocal variable_name.Final Answer:
nonlocal variable_name -> Option DQuick Check:
Correct nonlocal syntax = C [OK]
- Using 'global' instead of 'nonlocal'
- Writing 'local' or 'outer' which are invalid keywords
- Forgetting to write variable name after nonlocal
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
return x
print(outer())Solution
Step 1: Trace variable assignment
Variablexis set to 5 inouter(). The inner function declaresnonlocal xand setsx = 10.Step 2: Effect of nonlocal on
Thexnonlocalkeyword allowsinner()to modifyxinouter(). So after callinginner(),xbecomes 10.Final Answer:
10 -> Option AQuick Check:
nonlocal changes outer x to 10 = D [OK]
- Thinking x remains 5 because inner is separate
- Expecting a syntax error for nonlocal usage
- Assuming inner creates a new local x
def counter():
count = 0
def increment():
count = count + 1
return count
return increment()
print(counter())Solution
Step 1: Identify variable scope issue
Insideincrement(),count = count + 1tries to read and writecount. Withoutnonlocal, Python treatscountas local, but it is used before assignment.Step 2: Fix with
Addingnonlocalnonlocal counttells Python to use thecountfromcounter(), allowing modification.Final Answer:
Missing 'nonlocal count' inside increment() -> Option CQuick Check:
Modify outer variable needs nonlocal = A [OK]
- Using global instead of nonlocal
- Ignoring variable scope causing UnboundLocalError
- Returning count without incrementing properly
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?
Solution
Step 1: Understand closure with nonlocal
The functionmake_accumulator()returnsadd, which rememberstotal. Thenonlocal totalletsaddupdatetotaleach call.Step 2: Trace calls to
First call: total=0+5=5, prints 5.acc
Second call: total=5+3=8, prints 8.
Third call: total=8+(-2)=6, prints 6.Final Answer:
5 8 6 -> Option AQuick Check:
Accumulator sums values using nonlocal total = B [OK]
- Expecting total to reset each call
- Confusing nonlocal with global
- Thinking output is separate values, not cumulative
