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.

CategoryKeywords & Statements
KindKeyword / Statement
Python Versionall

📝 Syntax

global name [, name]*

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

2
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏