global Global declaration
Last updated: 2026-09-22
global Global declaration
global name declares that name refers to the module-level global inside a function.
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | all |
📝 Syntax
global name [, name]*
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
2
🏷️ Related Keywords / Statements
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QI can read a global variable without declaring `global`. Why do I still need it?
AReading is fine, but to modify a global variable you must declare `global`. Otherwise an `x += 1` inside the function treats `x` as local, raising `UnboundLocalError` or silently creating a local variable.
QWhat is the difference between `global` and `nonlocal`?
A`global` refers to a module-level (outermost) global variable. `nonlocal` is used inside nested functions and refers to a variable in the nearest enclosing function scope; it cannot point to a global.
QIs writing `global` at module top level useful?
ANo, and it is unnecessary — the module top level is already the global scope, so names there are global naturally. `global` only matters for declarations inside a function body.