Challenge - 5 Problems
Local Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of variable inside a function
What is the output of this code?
Python
def greet(): message = "Hello" print(message) greet()
Attempts:
2 left
๐ก Hint
Look where the variable
message is defined and where it is used.โ Incorrect
The variable
message is defined inside the function greet. When print(message) runs inside the function, it prints "Hello".โ Predict Output
intermediate2:00remaining
Accessing local variable outside function
What happens when you run this code?
Python
def show(): number = 10 show() print(number)
Attempts:
2 left
๐ก Hint
Think about where
number is defined and where you try to print it.โ Incorrect
The variable
number is local to the function show. It does not exist outside the function, so trying to print it outside causes a NameError.โ Predict Output
advanced2:00remaining
Local variable shadowing global variable
What is the output of this code?
Python
value = 5 def test(): value = 10 print(value) test() print(value)
Attempts:
2 left
๐ก Hint
Check which
value is printed inside and outside the function.โ Incorrect
Inside the function, the local
value is 10, so it prints 10. Outside, the global value is still 5, so it prints 5.โ Predict Output
advanced2:00remaining
Modifying global variable inside function without global keyword
What error or output does this code produce?
Python
count = 0 def increment(): count += 1 print(count) increment()
Attempts:
2 left
๐ก Hint
Think about how Python treats variables assigned inside functions.
โ Incorrect
Because
count is assigned inside the function, Python treats it as local. But it is used before assignment, causing an UnboundLocalError.โ Predict Output
expert3:00remaining
Understanding local scope with nested functions
Consider this code. What is the output when
outer() is called?Python
def outer(): x = 'local' def inner(): x = 'nonlocal' print(x) inner() print(x) outer()
Attempts:
2 left
๐ก Hint
Look at where
x is assigned inside inner() and how it affects outer().โ Incorrect
The
inner() function assigns a new local x that shadows the x in outer(). So inner() prints 'nonlocal', but outer()'s x remains 'local'.