Global
In one line
Global refers to variables defined at module level, and the global keyword lets functions modify them.
In simple words
A global variable is defined at the module level (outside any function or class). It is visible throughout the module. Inside functions, you can read global variables, but to modify them you need the global keyword.
Without global, assigning to a variable name inside a function creates a new local variable, even if a global with the same name exists. The global keyword tells Python to use the module-level variable instead.
Overusing global variables is generally discouraged because it makes code harder to test and debug. Prefer passing values as function parameters and returning results. Use global sparingly, mainly for module-level configuration.
Example
counter = 0 # global variable
def increment():
global counter # declare we want to modify the global
counter += 1
def read_counter():
return counter # reading globals doesn't need "global"
increment()
increment()
print(read_counter()) # 2Global variables are module-level. Use the global keyword inside functions to modify them.
Common confusions
Confused with: nonlocal
The difference: global modifies a module-level variable. nonlocal modifies a variable in an enclosing function (for nested functions/closures). Use global for module scope; nonlocal for enclosing function scope.
Related terms
Related Resources
Related Lessons
- Functions
Global keyword.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.