Challenge - 5 Problems
Global Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of modifying a global variable inside a function
What is the output of this Python code?
Python
x = 10 def modify(): global x x = 20 modify() print(x)
Attempts:
2 left
๐ก Hint
Think about how the 'global' keyword affects variable assignment inside functions.
โ Incorrect
The 'global' keyword tells Python to use the variable 'x' defined outside the function. So, when 'x' is assigned 20 inside 'modify()', it changes the global 'x'. Therefore, printing 'x' after calling 'modify()' outputs 20.
โ Predict Output
intermediate2:00remaining
Output when modifying a variable without global keyword
What will this code print?
Python
count = 5 def increment(): count = count + 1 increment() print(count)
Attempts:
2 left
๐ก Hint
Consider what happens when you assign to a variable inside a function without declaring it global.
โ Incorrect
Inside 'increment()', Python treats 'count' as a local variable because it is assigned to. But it is used before assignment in 'count = count + 1', causing an UnboundLocalError.
๐ง Debug
advanced2:00remaining
Fix the code to update global list inside function
This code tries to add an item to a global list inside a function. Which option correctly fixes it?
Python
items = [1, 2, 3] def add_item(): items = items + [4] add_item() print(items)
Attempts:
2 left
๐ก Hint
Remember that assigning to a variable inside a function creates a local variable unless declared global.
โ Incorrect
Option D correctly declares 'items' as global, so the assignment modifies the global list. Option D causes UnboundLocalError because 'items' is assigned inside the function without global. Option D avoids the function but does not fix the original code.
โ Predict Output
advanced2:00remaining
Output of nested function modifying global variable
What does this code print?
Python
value = 1 def outer(): def inner(): global value value = 5 inner() print(value) outer() print(value)
Attempts:
2 left
๐ก Hint
The inner function uses 'global' to change the variable. Think about when the print statements run.
โ Incorrect
The inner function sets the global 'value' to 5. The print inside 'outer()' prints the global 'value' which is now 5. The final print also prints 5 because the global variable was changed.
๐ง Conceptual
expert2:00remaining
Understanding global variable behavior with immutable types
Given this code, what is the value of 'num' after calling 'change()'?
Python
num = 10 def change(): global num num += 5 change()
Attempts:
2 left
๐ก Hint
The '+=' operator modifies the global variable when declared global.
โ Incorrect
The 'global' keyword allows the function to modify the global variable 'num'. The '+=' operator adds 5 to the current value, so 'num' becomes 15.