To use a global variable inside a function in Python, you need to explicitly declare it with the global
keyword if you intend to modify the variable. If you’re only reading its value, no special syntax is required. Here’s how to do it:
1. Modifying a Global Variable
Use the global
keyword inside the function to indicate you’re modifying the variable in the global scope.
Example:
x = 10 # Global variable
def update_global():
global x # Declare 'x' as global
x = 20 # Modify the global variable
update_global()
print(x) # Output: 20
2. Reading a Global Variable
No global
keyword is needed if you’re only accessing (not modifying) the variable.
Example:
x = 10
def read_global():
print(x) # Access global variable (no modification)
read_global() # Output: 10
3. Mutable Objects (Lists, Dictionaries)
For mutable objects (like lists), you can modify their contents without global
(e.g., appending items).
However, if you reassign the entire object, use global
.
Example:
my_list = [1, 2, 3] # Global list
def modify_list():
my_list.append(4) # Modifies the list in place (no 'global' needed)
def reassign_list():
global my_list
my_list = [5, 6, 7] # Reassigns the global variable
modify_list()
print(my_list) # Output: [1, 2, 3, 4]
reassign_list()
print(my_list) # Output: [5, 6, 7]
Common Pitfalls
Error: Forgetting global
when modifying a variable:
x = 10
def bad_example():
x = 20 # Creates a local variable, leaving the global 'x' unchanged
bad_example()
print(x) # Output: 10 (global 'x' wasn't modified)
Fix: Declare global x
inside the function.
Best Practices
Avoid global variables when possible. Instead:
- Pass values as arguments and return results.
- Use class attributes for shared state.
Example (Preferred Approach):
def process_data(value):
return value * 2 # No globals needed
result = process_data(5)
print(result) # Output: 10
Summary
Scenario | Syntax | Example |
---|---|---|
Modify a global variable | global var inside function | global x; x = 20 |
Read a global variable | No special syntax | print(x) |
Modify a mutable global object | No global needed (if not reassigning) | my_list.append(4) |
Reassign a mutable object | global var required | global my_list; my_list = [...] |
Use global
sparingly to avoid unintended side effects!