Bird
Raised Fist0
Pythonprogramming~10 mins

Nonlocal keyword in Python - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to modify the outer variable inside the inner function using the nonlocal keyword.

Python
def outer():
    count = 0
    def inner():
        [1] count
        count += 1
        return count
    return inner()

result = outer()
Drag options to blanks, or click blank then click option'
Adef
Bglobal
Cnonlocal
Dlocal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'global' instead of 'nonlocal' causes an error because 'count' is not global.
Forgetting to declare 'nonlocal' means the inner function creates a new local variable.
2fill in blank
medium

Complete the code to correctly increment the outer variable using the nonlocal keyword.

Python
def counter():
    num = 10
    def increment():
        [1] num
        num += 5
        return num
    return increment()

result = counter()
Drag options to blanks, or click blank then click option'
Adef
Bglobal
Clocal
Dnonlocal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'global' causes an error because 'num' is not a global variable.
Not declaring 'nonlocal' causes 'num' to be treated as local, leading to an UnboundLocalError.
3fill in blank
hard

Fix the error by adding the correct keyword to modify the outer variable inside the nested function.

Python
def make_multiplier():
    factor = 3
    def multiply(x):
        [1] factor
        factor += 1
        return x * factor
    return multiply

mult = make_multiplier()
result = mult(5)
Drag options to blanks, or click blank then click option'
Aglobal
Bnonlocal
Clocal
Ddef
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'global' causes an error because 'factor' is not global.
Omitting 'nonlocal' causes a local variable error.
4fill in blank
hard

Fill both blanks to correctly update the outer variable and return its new value.

Python
def accumulator():
    total = 0
    def add(value):
        [1] total
        total [2] value
        return total
    return add

acc = accumulator()
result = acc(7)
Drag options to blanks, or click blank then click option'
Anonlocal
B+=
C-=
Dglobal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'global' instead of 'nonlocal' causes errors.
Using '-=' instead of '+=' changes the logic incorrectly.
5fill in blank
hard

Fill all three blanks to create a nested function that modifies and returns the outer variable correctly.

Python
def counter(start):
    count = start
    def increment():
        [1] count
        count [2] 1
        return [3]
    return increment

inc = counter(100)
result = inc()
Drag options to blanks, or click blank then click option'
Anonlocal
B+=
Ccount
Dglobal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'global' instead of 'nonlocal' causes errors.
Returning a wrong variable or value.
Forgetting to declare 'nonlocal' causes UnboundLocalError.

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

  1. Step 1: Understand variable scopes

    Variables inside a function are local by default, and inner functions cannot change outer variables unless specified.
  2. Step 2: Role of nonlocal

    The nonlocal keyword allows the inner function to access and modify variables from the nearest enclosing function scope.
  3. Final Answer:

    Allows an inner function to modify a variable from its outer function. -> Option B
  4. Quick Check:

    nonlocal changes outer function variable = A [OK]
Hint: Nonlocal lets inner functions change outer variables [OK]
Common Mistakes:
  • Confusing nonlocal with global keyword
  • Thinking nonlocal creates new variables
  • Assuming nonlocal works outside functions
2. Which of the following is the correct syntax to use nonlocal inside a nested function?
easy
A. local variable_name
B. global variable_name
C. outer variable_name
D. nonlocal variable_name

Solution

  1. Step 1: Recall the syntax for nonlocal

    The keyword nonlocal is followed by the variable name to indicate it refers to an outer function's variable.
  2. Step 2: Compare options

    Only nonlocal variable_name uses the correct keyword and syntax: nonlocal variable_name.
  3. Final Answer:

    nonlocal variable_name -> Option D
  4. Quick Check:

    Correct nonlocal syntax = C [OK]
Hint: Use 'nonlocal' followed by variable name inside inner function [OK]
Common Mistakes:
  • Using 'global' instead of 'nonlocal'
  • Writing 'local' or 'outer' which are invalid keywords
  • Forgetting to write variable name after nonlocal
3. What will be the output of the following code?
def outer():
    x = 5
    def inner():
        nonlocal x
        x = 10
    inner()
    return x
print(outer())
medium
A. 10
B. None
C. Error: no binding for nonlocal 'x'
D. 5

Solution

  1. Step 1: Trace variable assignment

    Variable x is set to 5 in outer(). The inner function declares nonlocal x and sets x = 10.
  2. Step 2: Effect of nonlocal on x

    The nonlocal keyword allows inner() to modify x in outer(). So after calling inner(), x becomes 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    nonlocal changes outer x to 10 = D [OK]
Hint: nonlocal lets inner change outer variable value [OK]
Common Mistakes:
  • Thinking x remains 5 because inner is separate
  • Expecting a syntax error for nonlocal usage
  • Assuming inner creates a new local x
4. Find the error in this code snippet:
def counter():
    count = 0
    def increment():
        count = count + 1
        return count
    return increment()
print(counter())
medium
A. increment() should not return count
B. count should be global, not local
C. Missing 'nonlocal count' inside increment()
D. No error, code runs fine

Solution

  1. Step 1: Identify variable scope issue

    Inside increment(), count = count + 1 tries to read and write count. Without nonlocal, Python treats count as local, but it is used before assignment.
  2. Step 2: Fix with nonlocal

    Adding nonlocal count tells Python to use the count from counter(), allowing modification.
  3. Final Answer:

    Missing 'nonlocal count' inside increment() -> Option C
  4. 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

  1. Step 1: Understand closure with nonlocal

    The function make_accumulator() returns add, which remembers total. The nonlocal total lets add update total each call.
  2. 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.
  3. Final Answer:

    5 8 6 -> Option A
  4. 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