Fundamentals 4 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding the global Statement in Python

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:

count = 1

def cc():
    count = count + 1

cc()
# UnboundLocalError: local variable 'count' referenced before assignment

Correct usage with global:

def cc():
    global count
    count = count + 1
    print(count)

cc()
# 2

Multiple variables can be declared in one statement, separated by commas:

num = 0

def cc():
    global count, num
    count = count + 1
    num = num + 2
    print(count, num)

cc()
# 3 2

Alternatively, a class attribute can serve a similar purpose:

class C:
    count = 3

def cc():
    C.count = C.count + 1
    print(C.count)

cc()
# 4

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

fundamentalsVariable Scopeglobal
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.