Global Keyword
The global keyword tells Python that a variable inside a function refers to the global variable of the same name, rather than creating a new local variable - allowing the function to actually modify it.
Without the global Keyword
count = 0
def increment():
count = count + 1 # Error: local variable referenced before assignment
increment()
This raises an error because Python assumes count inside the function is a new local variable, and it hasn't been assigned a value yet at the point it's used.
Using the global Keyword
count = 0
def increment():
global count
count = count + 1
increment()
print(count) # 1
With global count declared, Python understands that count inside the function refers to the same variable defined outside it, so the update is reflected globally.
Coming Up Next
Now that you understand global variables and the global keyword, the next section looks more broadly at variable scope and how functions return values.