Junior — Middle
What is the role and purpose of the 'global' keyword in Python?
sobes.tech AI
Answer from AI
The global keyword in Python is used inside a function to indicate that the variable being referenced is in the global scope, not a local variable of the function. This allows modifying the value of a global variable from within the function.
Without global, assigning a value to a variable inside a function creates a new local variable with that name, without affecting the global one.
Example:
x = 10
def increment():
global x
x += 1
increment()
print(x) # Will output 11
If global x is removed, then a local variable x will be created inside the increment function, and the attempt x += 1 will cause an error because the local x is not initialized.