Skip to content
Home / Fundamentals

How to Use Global Variables in a Function in Python

In Python, a global variable is a variable that is defined outside of a function or in the global scope of a program. This means that the global variable can be accessed and modified from anywhere in the program. Global variables are often used to store values that need to be shared across different parts of a program, such as constants or configuration settings.

However, when working with functions, you may sometimes want to access or modify a global variable from within the function. In this case, you will need to use the global keyword to explicitly tell Python that you are working with the global variable and not a local variable with the same name.

Here is an example of how to use the global keyword to access and modify a global variable from within a function:

counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # Outputs 1

In this example, we define a global variable counter with a value of 0. We then define a function increment that uses the global keyword to access the global variable counter and increment its value by 1. When we call the increment function and then print the value of counter, we see that it has been incremented to 1.

It's important to note that using the global keyword to modify a global variable from within a function can have unintended consequences. For example, if multiple functions modify the same global variable, it can be difficult to keep track of the state of the variable and may lead to bugs in your program. In general, it is best to avoid using global variables and instead pass any necessary values as arguments to your functions.

Here is an example of how to pass a global variable as an argument to a function:

counter = 0

def increment(counter):
    counter += 1
    return counter

counter = increment(counter)
print(counter)  # Outputs 1

In this example, we define a global variable counter with a value of 0 and a function increment that takes a single argument counter. The function increments the value of counter by 1 and returns the new value. We then assign the returned value to the global variable counter, effectively incrementing its value by 1.

Using this approach, we can avoid using the global keyword and instead pass the necessary values to our functions as arguments. This can make our code easier to read and understand, and can help prevent unintended side effects caused by modifying global variables.