0
0
Pythonprogramming~20 mins

Enclosing scope in Python - Practice Problems & Coding Challenges

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

result = outer()
print(result)
A8
BTypeError
C5
DNameError
Attempts:
2 left
๐Ÿ’ก Hint
Remember that inner functions can access variables from their enclosing function.
โ“ Predict Output
intermediate
2:00remaining
Effect of modifying enclosing variable without nonlocal
What is the output of this code?
Python
def outer():
    x = 10
    def inner():
        x = 20
    inner()
    return x

print(outer())
ANone
B10
CUnboundLocalError
D20
Attempts:
2 left
๐Ÿ’ก Hint
Assigning to x inside inner creates a new local variable, not changing outer's x.
โ“ Predict Output
advanced
2:00remaining
Using nonlocal to modify enclosing variable
What is the output of this code?
Python
def outer():
    x = 1
    def inner():
        nonlocal x
        x += 5
    inner()
    return x

print(outer())
AUnboundLocalError
B1
CSyntaxError
D6
Attempts:
2 left
๐Ÿ’ก Hint
The nonlocal keyword allows inner to modify x in the outer scope.
โ“ Predict Output
advanced
2:00remaining
Output when accessing variable before assignment in nested function
What error does this code raise?
Python
def outer():
    x = 3
    def inner():
        print(x)
        x = 5
    inner()

outer()
AUnboundLocalError
BNameError
CSyntaxError
D3
Attempts:
2 left
๐Ÿ’ก Hint
Assigning to x inside inner makes x local, so print(x) tries to access before assignment.
๐Ÿง  Conceptual
expert
2:00remaining
How many items in the list after closure creation?
Consider this code that creates a list of functions inside a loop. How many functions in the list will return the value 4 when called?
Python
def make_funcs():
    funcs = []
    for i in range(5):
        def f():
            return i
        funcs.append(f)
    return funcs

funcs = make_funcs()
results = [func() for func in funcs]
print(results.count(4))
A0
B1
C5
D4
Attempts:
2 left
๐Ÿ’ก Hint
All functions capture the same variable i, which after the loop ends is 4.