0
0
Pythonprogramming~20 mins

Global scope in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Global Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A20
B10
CNameError
DNone
Attempts:
2 left
๐Ÿ’ก Hint
Think about how the 'global' keyword affects variable assignment inside functions.
โ“ Predict Output
intermediate
2: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)
AUnboundLocalError
B5
C6
DNameError
Attempts:
2 left
๐Ÿ’ก Hint
Consider what happens when you assign to a variable inside a function without declaring it global.
๐Ÿ”ง Debug
advanced
2: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)
AChange 'items = items + [4]' to 'items.append(4)' without global keyword.
BChange 'items = items + [4]' to 'items += [4]' without global keyword.
CRemove the function and add 4 directly to the list outside.
DAdd 'global items' inside the function before modifying it.
Attempts:
2 left
๐Ÿ’ก Hint
Remember that assigning to a variable inside a function creates a local variable unless declared global.
โ“ Predict Output
advanced
2: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)
A1\n5
B1\n1
C5\n5
D5\n1
Attempts:
2 left
๐Ÿ’ก Hint
The inner function uses 'global' to change the variable. Think about when the print statements run.
๐Ÿง  Conceptual
expert
2: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()
A10
B15
CTypeError
DUnboundLocalError
Attempts:
2 left
๐Ÿ’ก Hint
The '+=' operator modifies the global variable when declared global.