0
0
Pythonprogramming~10 mins

Nonlocal keyword in Python - Interactive Code Practice

Choose your learning style9 modes available
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.