Look at the code below. What will it print?
x = 5 def change(): global x x = 10 change() print(x)
Think about what the global keyword does inside a function.
The global keyword tells Python to use the variable x defined outside the function. So when x is set to 10 inside change(), it changes the global x. The print statement then shows 10.
What error will this code produce?
count = 0 def increment(): count += 1 increment()
Look at how count is used inside the function without global.
Inside increment(), Python treats count as a local variable because it is assigned to. But it is used before assignment, causing an UnboundLocalError.
Fix the code so that print(x) outputs 1.
x = 0 def set_x(): x = 1 set_x() print(x)
Think about how to modify the global variable inside a function.
Without global x, the assignment x = 1 creates a new local variable x inside the function. The global x remains 0. Adding global x tells Python to use the global variable.
What will this code print?
count = 0 def outer(): def inner(): global count count += 1 inner() outer() print(count)
Notice the use of global inside the inner function.
The global count inside inner() means it modifies the global count. So count increases from 0 to 1. The print shows 1.
Which code snippet will raise an error because of wrong use of the global keyword?
Consider if the global variable is initialized before use.
Option B raises a NameError: name 'c' is not defined. The global c declaration is used, but c += 1 requires reading the global c first, which does not exist yet. Simple assignment would create it, but read-modify-write operations like += fail if undefined.
Option B: Reads existing global b, fine.
Option B: Assigns to undefined a, creating it globally, fine.
Option B: Reads existing d (initialized to 0) and updates it, fine.