Recall & Review
beginner
What does the
global keyword do in Python?The
global keyword tells Python that a variable inside a function refers to the variable defined outside the function, at the global level. It allows you to change the global variable from inside the function.Click to reveal answer
beginner
Why do you need the
global keyword to modify a global variable inside a function?Without
global, Python treats variables assigned inside a function as local. Using global tells Python to use the variable from outside the function, so changes affect the global variable.Click to reveal answer
beginner
What happens if you try to modify a global variable inside a function without using
global?Python creates a new local variable with the same name inside the function. The global variable remains unchanged outside the function.
Click to reveal answer
beginner
Show a simple example of using
global to change a global variable inside a function.Example:
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1Click to reveal answer
intermediate
Can the
global keyword be used to create a new global variable inside a function?Yes. If the global variable does not exist yet, using
global inside a function and assigning a value will create it at the global level.Click to reveal answer
What does the
global keyword do inside a function?✗ Incorrect
The
global keyword lets you modify a variable defined outside the function.What happens if you assign a value to a variable inside a function without using
global?✗ Incorrect
Without
global, assignment creates a new local variable.Which keyword do you use to tell Python to use the global variable inside a function?
✗ Incorrect
The
global keyword is used to access and modify global variables.Can you create a new global variable inside a function using
global?✗ Incorrect
Using
global and assigning a value inside a function creates a new global variable.What will this code print?
count = 5
def change():
count = 10
change()
print(count)✗ Incorrect
Without
global, count = 10 creates a local variable. The global count stays 5.Explain how the
global keyword affects variable scope inside a function.Think about how Python treats variables inside functions by default.
You got /4 concepts.
Describe a situation where you would need to use the
global keyword in your code.Consider when a function needs to update a value defined outside it.
You got /4 concepts.