0
0
Pythonprogramming~20 mins

Nonlocal keyword in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Nonlocal Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Understanding nonlocal variable modification
What is the output of this code?
Python
def outer():
    x = 5
    def inner():
        nonlocal x
        x = 10
    inner()
    return x

result = outer()
print(result)
A10
B5
CUnboundLocalError
DNone
Attempts:
2 left
๐Ÿ’ก Hint
Remember that 'nonlocal' allows inner functions to modify variables in the nearest enclosing scope.
โ“ Predict Output
intermediate
2:00remaining
Nonlocal with multiple nested functions
What will be printed by this code?
Python
def a():
    x = 1
    def b():
        x = 2
        def c():
            nonlocal x
            x = 3
        c()
        return x
    return b()

print(a())
A1
BUnboundLocalError
C2
D3
Attempts:
2 left
๐Ÿ’ก Hint
The 'nonlocal' keyword affects the nearest enclosing scope, not the global or outermost.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error caused by missing nonlocal
What error does this code raise when run?
Python
def outer():
    count = 0
    def inner():
        count += 1
        return count
    return inner()

print(outer())
AUnboundLocalError
BTypeError
CSyntaxError
D0
Attempts:
2 left
๐Ÿ’ก Hint
Think about what happens when you try to change a variable from an outer scope without 'nonlocal'.
โ“ Predict Output
advanced
2:00remaining
Effect of nonlocal on mutable objects
What is the output of this code?
Python
def outer():
    data = [1, 2, 3]
    def inner():
        data.append(4)
    inner()
    return data

print(outer())
A[1, 2, 3]
B[1, 2, 3, 4]
CSyntaxError
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Check if 'nonlocal' can be used with mutable objects like lists.
โ“ Predict Output
expert
2:00remaining
Complex nested nonlocal variable changes
What is the output of this code?
Python
def f():
    x = 0
    def g():
        nonlocal x
        x = 1
        def h():
            nonlocal x
            x = 2
        h()
        return x
    return g()

print(f())
A1
B0
C2
DUnboundLocalError
Attempts:
2 left
๐Ÿ’ก Hint
Follow how 'nonlocal' changes the same variable 'x' in nested functions.