Question
How can you create or use a global variable inside a Python function?
How can a variable defined outside a function, or assigned in one function, be accessed from other functions?
A common issue is forgetting to use the global keyword when reassigning a global name inside a function, which can lead to UnboundLocalError.
For example:
count = 0
def increment():
global count
count += 1
def show():
print(count)
In this situation, what are the rules for reading and modifying global variables from functions in Python?
Short Answer
By the end of this page, you will understand what a global variable is in Python, how functions read and modify global names, when to use the global keyword, and why UnboundLocalError happens. You will also see safer alternatives that are usually better in real programs.
Concept
In Python, a global variable is a name defined at the module level, outside any function.
message = "Hello"
Here, message is global to that file.
Inside a function, Python follows name lookup rules to decide where a variable comes from. A function can usually read a global variable without any special keyword:
message = "Hello"
def greet():
print(message)
But if you assign to that name inside the function, Python treats it as a local variable unless you explicitly say otherwise.
message = "Hello"
def greet():
message = "Hi"
print(message)
In this case, message inside greet() is local, not global.
If you want to modify the global variable itself, you must use global:
message = "Hello"
def update_message():
message
message =
Mental Model
Think of a Python file as an office building.
- A global variable is a notice board in the main lobby.
- A function is a private room.
- People inside a room can read the notice board in the lobby.
- But if they want to replace the notice on the lobby board, they must explicitly say: I am updating the lobby board.
That explicit statement is the global keyword.
Without it, if someone writes a new note inside the room, Python assumes it belongs only to that room.
So:
- Read only: you can look at the lobby board.
- Assign/update: you must declare
globalto change the lobby board. - Otherwise, Python assumes you are creating a room-only note.
Syntax and Examples
Basic syntax
Read a global variable
name = "Alice"
def show_name():
print(name)
This works because the function only reads name.
Modify a global variable
name = "Alice"
def change_name():
global name
name = "Bob"
This changes the module-level variable.
Example: reading vs writing
score = 10
def display_score():
print("Current score:", score)
def add_bonus():
global score
score += 5
display_score()
add_bonus()
display_score()
Output:
Current score: 10
Current score: 15
Why global is needed in
Step by Step Execution
Trace example
count = 1
def increase():
global count
count = count + 2
def show():
print(count)
show()
increase()
show()
What happens step by step
-
count = 1- A global variable named
countis created.
- A global variable named
-
increase()is defined.- The function exists, but does not run yet.
-
show()is defined.- This function also exists, but does not run yet.
-
show()is called.- Python looks for
count. - There is no local
countinsideshow(), so it reads the globalcount. - It prints
1.
- Python looks for
Real World Use Cases
Global variables do appear in real programs, but usually in limited, careful ways.
Common practical uses
Module-level configuration
DEBUG = True
API_URL = "https://example.com/api"
Functions may read these values across the file.
Shared constants
TAX_RATE = 0.15
MAX_RETRIES = 3
These are usually safe because they are not meant to change.
Small scripts
In a short automation script, a simple counter or status flag may be kept globally.
Caching or state in simple programs
A quick prototype may store a loaded resource in a global variable.
cache = {}
Where globals are less ideal
- Web applications
- Large codebases
- Multi-threaded programs
- Reusable libraries
- Unit-tested business logic
In these cases, passing data through parameters or using classes is usually clearer and safer.
Real Codebase Usage
In real codebases, developers usually try to avoid mutable global state because it creates hidden dependencies between functions.
Common patterns instead of globals
1. Pass values as parameters
def add_bonus(score):
return score + 5
This is easier to test and reuse.
2. Return updated values
def increment(count):
return count + 1
count = 0
count = increment(count)
3. Use configuration constants at module level
TIMEOUT = 30
def fetch_data():
print(f"Using timeout: {TIMEOUT}")
Reading constants globally is common.
4. Use objects to hold shared state
class Counter:
def __init__(self):
.count =
():
.count +=
Common Mistakes
1. Reassigning a global without global
Broken code:
total = 0
def add():
total += 1
Problem:
- Python treats
totalas local because it is assigned inside the function. - It tries to read the local variable before assignment.
Fix:
total = 0
def add():
global total
total += 1
2. Thinking global is needed just to read a variable
Broken idea:
value = 10
def show():
global value
print(value)
This is not broken, but the global keyword is unnecessary here.
Better:
value = 10
():
(value)
Comparisons
Global variables vs local variables
| Concept | Global variable | Local variable |
|---|---|---|
| Defined where | Outside functions | Inside a function |
| Visible where | Across the module | Only inside that function |
| Can be read in function | Yes | Yes, in its own function |
| Reassignment inside function | Requires global | No special keyword needed |
| Typical use | Constants, shared config, simple state | Temporary function data |
Reading vs modifying globals
| Action inside function | Needs global? | Example |
|---|
Cheat Sheet
Quick rules
- A global variable is defined outside functions.
- You can read a global variable inside a function without
global. - You must use
globalif you assign to that global name inside the function. x += 1counts as assignment.- Mutating an object like
items.append()is different from reassigningitems.
Syntax
Read global
value = 10
def show():
print(value)
Modify global
value = 10
def change():
global value
value = 20
Create global inside function
def setup():
global config
config = {}
Common error
FAQ
Why can I read a global variable in Python without using global?
Because reading does not create a local variable. Python looks for the name in local scope first, then outer scopes, then global scope.
Why does count += 1 need the global keyword?
Because it reassigns the name count. Python treats that as a local assignment unless you declare it as global.
Does modifying a list or dictionary require global?
Not if you are mutating the existing object, such as with append() or key assignment. But if you reassign the variable name to a new object, then yes.
Can I create a global variable from inside a function?
Yes, by using global, but it is usually better to return a value and assign it outside the function.
Is using global variables bad practice in Python?
Not always, but mutable globals are often discouraged because they make code harder to reason about and test.
What is the difference between global and nonlocal?
global refers to a module-level variable. nonlocal refers to a variable in an enclosing function.
Mini Project
Description
Build a small Python program that tracks how many tasks have been completed. This project demonstrates reading and updating a global variable from different functions, while also showing where global is required.
Goal
Create a task counter that can display the current count, increment it, and reset it.
Requirements
- Create a global variable to store the number of completed tasks.
- Write one function that displays the current count.
- Write one function that increments the count.
- Write one function that resets the count to zero.
- Call the functions to show that the global state changes across function calls.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.