python how to use global variables

Published on Aug. 22, 2023, 12:15 p.m.

To use global variables in Python, you need to first declare them outside any functions or classes using the global keyword. This tells Python that the variable should have global scope, which means it can be accessed and modified from anywhere in the program.

Here’s an example:

# Define a global variable
global_var = "Hello world!"

# Define a function that modifies the global variable
def modify_global():
    global global_var
    global_var = "Goodbye world!"

# Call the function to modify the global variable
modify_global()

# Print the new value of the global variable
print(global_var)

In this example, we define a global variable called global_var and a function called modify_global() that modifies the value of the global variable. To indicate that we want to modify the global variable within the function, we use the global keyword followed by the name of the global variable.

Finally, we call the function and then print the new value of the global variable. Note that the global keyword is not used when accessing a global variable, only when modifying it.

Tags:

related content