How to make a global variable in Python

How to create a global variable in Python, with a simple example: learn how to make your code accessible across different modules.

Creating a Global Variable in Python

A global variable is a variable that is accessible from anywhere in the program. To create a global variable in Python, you simply use the global keyword. This keyword is used to indicate that the variable is not local to the scope of the function in which it is declared. To illustrate how this works, let’s look at a simple example.


# Declaring a global variable
global my_var

# Setting a value for the global variable
my_var = 10

# Function to use the global variable
def some_func():
    # Accessing the global variable
    print(my_var)

# Calling the function
some_func()

In the code above, we declared a global variable my_var and set its value to 10. We then created a function some_func that prints the value of the global variable. When we call the function, it prints the value 10, which is the value of my_var. Note that we didn’t have to pass the variable to the function as an argument. This is because it is a global variable and is accessible from any scope.

Global variables are useful for maintaining state across multiple functions. However, they should be used with caution as they can cause bugs if not used correctly. For example, if you change the value of a global variable in one function, it will affect all other functions that use the variable. This can lead to unexpected behavior and can be difficult to debug.

Answers (0)