Challenge - 5 Problems
Enclosing Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2: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)
Attempts:
2 left
๐ก Hint
Remember that inner functions can access variables from their enclosing function.
โ Incorrect
The inner function accesses the variable x from the outer function's scope and adds 3, so 5 + 3 = 8.
โ Predict Output
intermediate2: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())
Attempts:
2 left
๐ก Hint
Assigning to x inside inner creates a new local variable, not changing outer's x.
โ Incorrect
The assignment inside inner creates a new local x, so outer's x remains 10.
โ Predict Output
advanced2: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())
Attempts:
2 left
๐ก Hint
The nonlocal keyword allows inner to modify x in the outer scope.
โ Incorrect
nonlocal x lets inner modify the x defined in outer, so x becomes 1 + 5 = 6.
โ Predict Output
advanced2: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()
Attempts:
2 left
๐ก Hint
Assigning to x inside inner makes x local, so print(x) tries to access before assignment.
โ Incorrect
Python treats x as local in inner due to assignment, so print(x) before assignment causes UnboundLocalError.
๐ง Conceptual
expert2: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))
Attempts:
2 left
๐ก Hint
All functions capture the same variable i, which after the loop ends is 4.
โ Incorrect
All functions refer to the same i, which is 4 after the loop, so all return 4, count is 5.