Challenge - 5 Problems
Nonlocal Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2: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)
Attempts:
2 left
๐ก Hint
Remember that 'nonlocal' allows inner functions to modify variables in the nearest enclosing scope.
โ Incorrect
The 'nonlocal' keyword lets the inner function change the variable 'x' defined in the outer function. So after calling inner(), x becomes 10.
โ Predict Output
intermediate2: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())
Attempts:
2 left
๐ก Hint
The 'nonlocal' keyword affects the nearest enclosing scope, not the global or outermost.
โ Incorrect
Inside function c(), 'nonlocal x' refers to x in function b(). So c() changes b()'s x to 3. But b() returns x after c() runs, which is 3. However, b()'s x was initially 2 and changed to 3 by c(), so the return is 3.
๐ง Debug
advanced2: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())
Attempts:
2 left
๐ก Hint
Think about what happens when you try to change a variable from an outer scope without 'nonlocal'.
โ Incorrect
The inner function tries to increment 'count' but Python treats 'count' as a local variable because of the assignment. Since 'count' is used before assignment, it raises UnboundLocalError.
โ Predict Output
advanced2: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())
Attempts:
2 left
๐ก Hint
Check if 'nonlocal' can be used with mutable objects like lists.
โ Incorrect
The inner() function modifies the 'data' list from the outer() scope by appending 4. Since 'data' is a mutable object, it can be modified without declaring 'nonlocal'. So outer() returns [1, 2, 3, 4].
โ Predict Output
expert2: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())
Attempts:
2 left
๐ก Hint
Follow how 'nonlocal' changes the same variable 'x' in nested functions.
โ Incorrect
Function g() declares 'nonlocal x' referring to f()'s x. It sets x=1. Then h() also declares 'nonlocal x' referring to the same x and sets x=2. So after h() runs, x is 2. g() returns x, so f() returns 2.