How to Use a Global Variable in a Function in Python?

How to Use a Global Variable in a Function in Python?

Answer: You can use a global variable in a function by modifying it with the global keyword and passing it as an argument.

Using a global variable in a function allows you direct access with the global keyword. It can also be passed as an argument to the function. Another option is to store it in structures like dictionaries or objects for easier handling.

Table of Contents: 

Methods to Use a Global Variable in a Function in Python

Python provides various methods to use a global variable in a function in Python. Following are some of these methods explained with examples:

Method 1: Using the Global Keyword in Python

The global keyword allows you to modify a global variable inside a function. 

Example:

Python
# Declare a global variable
x = 10
# Using the global keyword function to modify x
def update_global():
# Declare x as global to modify it
global x
# Modify the global variable
x = 20
# Update the global variable defined
update_global()
# Print the updated global variable
print("The updated global variable:",x )
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 76

Explanation:

The global keyword is used to modify a global variable inside the function. In the example, the value of x is updated from 10 to 20.

Method 2: Using the globals() Function in Python

The globals() function allows you to access and modify global variables. It returns a dictionary containing all global names and their values.

Example:

Python
# Declare global variables
a = 30
b = 60
c = 90
# Function using globals() to access and modify global variables
def print_globals():
# Print the variables a, b and access c using globals()
print(a, b, globals()["c"])
# Update the global variable c
globals()["c"] = 300
# Print the updated global variable c
print(c)
# Call the function
print_globals()
# Print the global variable c
print(c)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 77

Explanation:

The global() returns a dictionary containing all global variables. Inside the function, we use global() [“c”] to access the global c, even if local c  is already defined. 

Method 3: Using a Global Dictionary in Python

You can store global variables in a dictionary and then access or modify them inside functions. 

Example:

Python
# Declare a global dictionary with variables
global_variables = {'a': 10, 'b': 20, 'c': 30}
# Function to modify the global dictionary
def update_global_dict():
# Access the global dictionary
global global_variables
# Modify the value of 'a'
global_variables['a'] = 100
# Modify the value of 'c'
global_variables['c'] = 200
# Call the function to update the global dictionary
update_global_dict()
# Print the updated global dictionary
print("The global variables are:",global_variables)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 78

Explanation:

In the update_global_dict(), we access the dictionary using the global keyword and update the values of ‘a’ and ‘c’. A global dictionary can hold multiple global variables. This method is useful for managing several global variables together.

Method 4: Using Environment Variables (os.environ) in Python

The environment variables can be used to store and access global data in Python. The os.environ provides access to environment variables.

Example:

Python
# Import the os module
import os
# Set the Environment (Global) Variable
os.environ['GLOBAL_VAR'] = '18'
def get_global():
# Update the global variable
return int(os.environ['GLOBAL_VAR']) + 7
# Print the updated global variable
print("The updated global variable:", get_global())
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Explanation: Environment variables are accessed through os.environ, and here, ‘GLOBAL_VAR’ is defined as 18 to 25.

Method 5: Using a Class Variable (self.variable) in Python

Global variables can be defined as class variables and then accessed through the class or an instance.

Example:

Python
class GlobalContainer:
# Define the class variable which is the global variable here
x = "Intellipaat"
@staticmethod
def modify_global():
# Concatenation of the global variable
GlobalContainer.x += " Blogs"
GlobalContainer.modify_global()
print(GlobalContainer.x)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 79

Explanation:

Here, the global variable is defined as class variable x, which is modified using a static method by concatenating ” Blogs”, and then printing the ”Intellipaat Blogs”.

Method 6: Using the Mutable Datatypes (Lists and Tuples) in Python

The mutable datatypes like lists and tuples help in the modification of the global variables without using the global keyword.

Example:

Python
# Initialize the global variable in the form of a list with some values
global_var = ["Intellipaat is an excellent"]
def modify_global(lst):
# Update the existing global variable
lst[0] += " platform for upskilling"
modify_global(global_var)
print(global_var[0])
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 80

Explanation: 

Here the global variable is defined in the form of a list. Lst[0] updates the global variable defined and returns the updated global variable as “Intellipaat is an excellent platform for upskilling.

Method 7: Using a Singleton Class in Python

A singleton function ensures that a global variable is managed within a single instance, maintaining consistency across the program.

Example:

Python
class GlobalVars:
# Define Singleton Instance
_instance = None
def __new__(cls):
# Ensure only one instance of the class is created
if cls._instance is None:
cls._instance = super(GlobalVars, cls).__new__(cls)
# Initializing strings to the global variable 'x' within the Singleton Instance
cls._instance.x = "Intellipaat provides flexible learning options"
return cls._instance
def modify_global(self):
# Modify the global variable within the singleton instance
self.x += " and ensures practical learning."
# Create a singleton instance
global_instance = GlobalVars()
global_instance.modify_global()
# Print the updated global variable
print(global_instance.x)
 
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:

image 81

Explanation:

Here, the implementation of the singleton class ensures that only one instance manages the global variable x. The modify_global()  updates the value of the global variable x and returns 

“Intellipaat provides flexible learning options and ensures practical learning”.

Conclusion

Python global variables can be controlled in several ways, each fulfilling different purposes. The global keyword or globals() gives direct access, and dictionaries and class variables give structured storage. Mutable types permit changes without the global keyword, and singleton classes provide a controlled global state. Understanding these methods helps you effectively use the global variable in a function in Python.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner