Using global variables in a Python function


In Python, a global variable is a variable that is defined outside of any function or class and is accessible to all functions and classes within the same module.


Here is an example of the usage of a global variable:

my_global_var = "Hello"

def my_function():
    global my_global_var
    my_global_var = "World"
    print("Inside function:", my_global_var)

print("Before function:", my_global_var)
my_function()
print("After function:", my_global_var)

In this example, the my_global_var variable is defined outside the function and initialized with the value "Hello". Inside the my_function() function, the global keyword is used to indicate that the function should use the global my_global_var variable. The value of my_global_var is then changed to "World" and printed out inside the function.


When the function is called, the output will be:

Before function: Hello
Inside function: World
After function: World

As you can see, the value of my_global_var has been changed inside the function and this change is reflected outside the function as well.


Note that using global variables can make your code harder to read and maintain, and it is generally considered good practice to avoid them whenever possible. Instead, you can pass variables as arguments to functions and return values from functions to achieve the desired functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *