Understanding the global Statement in Python
The article explains how Python's global statement declares variables as global within a function, allowing modification of module‑level variables and preventing UnboundLocalError, with examples of incorrect usage, correct usage, multiple globals, and class‑based alternatives.
When a function needs to modify a variable defined outside its scope, Python requires the global statement to declare that variable as global; otherwise the interpreter treats assignments as creating a new local variable, leading to errors such as UnboundLocalError .
Example of the error:
<code>count = 1
def cc():
count = count + 1
cc()
# UnboundLocalError: local variable 'count' referenced before assignment</code>Correct usage with global :
<code>def cc():
global count
count = count + 1
print(count)
cc()
# 2</code>Multiple variables can be declared in one statement, separated by commas:
<code>num = 0
def cc():
global count, num
count = count + 1
num = num + 2
print(count, num)
cc()
# 3 2</code>Alternatively, a class attribute can serve a similar purpose:
<code>class C:
count = 3
def cc():
C.count = C.count + 1
print(C.count)
cc()
# 4</code>The global statement therefore acts like passing a variable into a function, allowing the function to read and modify the variable defined in the outer (module) scope.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.