Using global variables in a function

In Python, you can use global variables in a function by declaring the variable as global within the function. Here's an example:

x = 10

def foo():
    global x
    x = 20

print(x)  # prints 10
print(x)  # prints 20

In this example, x is a global variable that is defined outside of the foo function. Within the foo function, we declare x as a global variable using the global keyword. This allows us to modify the value of x within the function. When we call the function and then print the value of x, we see that it has been changed to 20.

Watch a course Python - The Practical Guide

Keep in mind that global variables should generally be used sparingly, as they can make code harder to understand and maintain. In most cases, it is better to pass values into a function as arguments and return values from the function using the return statement.