Overview: Global Variables in Python
Suppose several functions need to use the same value. If each function creates its own variable, the same value must be defined separately in each function. This can lead to longer, repetitive code and make the program harder to manage.
To solve this problem, Python provides global variables.
Introduction: What Are Global Variables in Python?
Definition: Global variables are variables that Python creates outside all functions. Because they are created outside functions, they belong to the global scope and can be accessed from different parts of the program, including inside functions.
Global variables are useful when the same value needs to be available to multiple functions or other parts of a program. Instead of creating the same variable separately inside each function, a single global variable can provide the shared value.
For example, a program may need to use the same tax rate, application name, or configuration value in several functions. A global variable can store that shared value so the functions can access it when needed.
How to Create Global Variables in Python
Creating global variables is simple. Define the variable outside all functions, then use it wherever the value is needed.
- Define the variable outside all functions.
- Assign a value to the variable.
- Access the variable inside a function when needed.
message = "Hello"
def greet():
print(message)
greet()
# Output:
Hello
Explanation: Here, the message variable is created outside the greet() function, so it is a global variable. The function can access and use its value.
Accessing a Global Variable Inside a Function
A function can read a global variable when it does not have a local variable with the same name.
language = "Python"
def show_language():
print(language)
show_language()
# Output:
Python
Explanation: Here, the show_language() function does not define its own language variable, so Python uses the global language variable.
What Happens When a Function Modifies a Global Variable?
A function can read a global variable, but assigning a new value to it inside the function requires special handling. Let’s see what happens:
count = 10
def increase():
count += 1
increase()
# Error:
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Explanation: When increase() runs, Python treats count as a local variable because the function assigns a new value to it. It therefore cannot use the existing global count in count += 1. The global keyword allows the function to modify the global variable.
Rules of Global Variables
Here are the main rules to remember when working with global variables in Python:
- A global variable is created outside all functions.
- A function can read a global variable without using the
globalkeyword. - If a function assigns a value to a variable, Python normally treats that variable as local to the function.
- The
globalkeyword allows a function to modify a global variable. - A local variable with the same name takes priority inside its function.
Use Cases of Global Variables
Here are some of the important use cases of global variables in Python:
- Sharing a common program setting
- Sharing configuration values across functions
- Maintaining a counter used by multiple functions
- Storing a value that several functions need to read
- Maintaining shared state in small programs
Practical Examples of Global Variables
The following examples will help you understand how global variables in Python are used in practical situations:
Example 1: Sharing a Program Setting
app_name = "Student Portal"
def show_header():
print("Welcome to", app_name)
def show_footer():
print("Thank you for using", app_name)
show_header()
show_footer()
# Output:
Welcome to Student Portal
Thank you for using Student Portal
Explanation: When show_header() runs, it reads app_name from the global scope and prints the welcome message. When show_footer() runs, it reads the same global variable and prints the footer message.
Example 2: Sharing a Configuration Value
tax_rate = 0.05
def calculate_price(price):
return price + (price * tax_rate)
print(calculate_price(1000))
# Output:
1050.0
Explanation: When calculate_price(1000) runs, the function reads the global tax_rate and uses it to calculate the final price. The global keyword is not needed because the function only reads tax_rate.
Example 3: Using a Shared Configuration in Multiple Functions
tax_rate = 0.10
def calculate_tax(price):
return price * tax_rate
def show_tax(price):
print("Tax:", price * tax_rate)
print(calculate_tax(500))
show_tax(500)
# Output:
50.0
Tax: 50.0
Explanation: When calculate_tax(500) runs, it reads the global tax_rate and returns 50.0. Then show_tax(500) reads the same global value and prints the tax. Neither function needs the global keyword because both functions only read tax_rate.
Example 4: Using the Same Global Value in Multiple Functions
language = "Python"
def show_language():
print(language)
def display_language():
print("Learning", language)
show_language()
display_language()
# Output:
Python
Learning Python
Explanation: When show_language() runs, it reads the global language and prints its value. When display_language() runs, it reads the same global variable and uses it in another message.
Example 5: Sharing a Counter Between Functions
visitor_count = 0
def add_visitor():
global visitor_count
visitor_count += 1
def show_visitors():
print("Visitors:", visitor_count)
add_visitor()
add_visitor()
show_visitors()
# Output:
Visitors: 2
Explanation: The first call to add_visitor() changes the global visitor_count from 0 to 1. The second call changes it to 2. When show_visitors() runs, it reads the updated value and prints 2. The global keyword allows add_visitor() to modify the global variable.
Common Mistakes With Global Variables
Here are some common mistakes to avoid when working with global variables in Python.
- Modifying a Global Variable Without
global - Accidentally Creating a Local Variable With the Same Name
- Trying to Access a Local Variable as a Global Variable
1. Modifying a Global Variable Without global
count = 10
def increase():
count += 1
increase()
# Error:
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Explanation: Because count is assigned inside the function, Python treats it as a local variable. The function therefore cannot use count += 1 to modify the global variable without the global keyword.
2. Accidentally Creating a Local Variable With the Same Name
count = 10
def show_count():
count = 20
print(count)
show_count()
print(count)
# Output:
20
10
Explanation: The count created inside show_count() is a local variable. It has the same name as the global count, but it does not change the global variable. The function prints 20, while the global variable remains 10.
3. Trying to Access a Local Variable as a Global Variable
def show():
message = "Hello"
show()
print(message)
# Error:
NameError: name 'message' is not defined
Explanation: The message variable is created inside show(), so it belongs to the function’s local scope. Code outside the function cannot access it as a global variable.
For more information, see Python Local Variables.
Note: The concepts covered in this tutorial on global variables will be clearer once you understand local variables and the related topics below.
Related Topics
Some global-variable concepts also apply to local variables. These shared topics are covered separately to avoid repeating the same explanation.
Key Takeaways: Global Variables
Here are the key points to remember about global variables in Python.
- Global variables are created outside functions and can be shared across different parts of a program.
- Functions can read global variables without using the
globalkeyword. - Use
globalwhen a function needs to modify a global variable. - Use global variables carefully to keep shared program state manageable.