Skip to content

Module 9 · Functions — topic 14 of 19

Global variables

Module-level names, reading them from functions, changing them with the global statement, and why shared mutable state should be kept to a minimum.

Beginner 8 min read·Lesson 139 of 306 in Python Programming

Learning objectives

  • Read global constants from functions
  • Use the global statement correctly when necessary
  • Explain the drawbacks of mutable global state

Definition

A global variable is a name defined at the top level of a module. Functions can read globals directly; to rebind a global from inside a function, the function must declare it with the global statement.

Introduction

Values like TAX_RATE = 0.18 or MAX_USERS = 100 are naturally global: many functions use them and they don't change. Mutable global state, however, quickly makes programs hard to follow.

Why it matters

Knowing when globals are fine (constants, configuration) and when they hurt (counters, caches modified from everywhere) is an important design skill.

Detailed explanation

A function can read any global name that it doesn't also assign. Reading works because Python looks in the local scope first, then the global scope.

To rebind a global inside a function, declare it: global counter. Without the declaration, assignment creates a local.

Mutating a global object (appending to a global list) doesn't need global, because it doesn't rebind the name — but it is still a hidden side effect.

Globals make functions depend on invisible state: their behaviour changes depending on what other code did earlier, which makes testing and debugging harder.

Convention: constants are written in UPPER_CASE at the top of a module and never reassigned.

Syntax

Python
TAX_RATE = 0.18 # global constant (read-only)
calls = 0 # global state
def price_with_tax(p):
return p * (1 + TAX_RATE) # reading is fine
def record_call():
global calls # needed to rebind
calls += 1
  • Reading a global needs no declaration.
  • Rebinding needs global.
  • Prefer constants over mutable globals.

Code examples

Reading a global constant

Python
TAX_RATE = 0.18
def price_with_tax(price):
return round(price * (1 + TAX_RATE), 2)
print(price_with_tax(250))
Output
295.0

The global statement

Python
calls = 0
def record_call():
global calls
calls += 1
for _ in range(3):
record_call()
print(calls)
Output
3

More examples

Replacing hidden state with explicit state

Python
# Global version: works, but every function depends on hidden state
balance = 0
def deposit(amount):
global balance
balance += amount
deposit(100)
deposit(50)
print("global:", balance)
# Explicit version: state passed in and returned
def deposit_to(current, amount):
if amount <= 0:
raise ValueError("amount must be positive")
return current + amount
wallet = 0
wallet = deposit_to(wallet, 100)
wallet = deposit_to(wallet, 50)
print("explicit:", wallet)
Output
global: 150
explicit: 150

Step-by-step explanation

  • The first version changes a module-level balance through global — any function anywhere could change it too.
  • The second version receives the current value and returns the new one; its result depends only on its arguments.
  • Pure functions like deposit_to are easy to test: deposit_to(0, 100) is always 100.

Expected output

Running “Replacing hidden state with explicit state” prints exactly:

TextOutput
global: 150
explicit: 150

Practical applications

  • Configuration constants and lookup tables are typical globals.
  • Larger programs hold state in objects (classes) rather than globals.

Best practices

  • Use globals for constants only, in UPPER_CASE.
  • Pass state as parameters and return new values.
  • Group related changing state into objects.

Common mistakes

Assigning without global

Avoid

count = 0
def inc():
count = count + 1

Prefer

count = 0
def inc():
global count
count = count + 1

Without global, count is local and read before assignment: UnboundLocalError.

Overusing global

Avoid

Ten functions all reading and writing the same globals.

Prefer

Group the state into a class or pass it explicitly.

Hidden shared state makes bugs depend on call order.

Important notes

  • global applies to module-level names; for an enclosing function's variable use nonlocal (see Scope).

Key takeaways

  • Functions can read globals freely.
  • Rebinding a global requires the global statement.
  • Mutable global state makes code hard to test; prefer explicit state.

Try it yourself

  1. 1
    Convert a program that keeps a high score in a global into one that passes it around.
  2. 2
    Define three UPPER_CASE constants and use them in two functions.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic