Python Global Keyword with example

In Python, a global keyword is used to indicate that a variable is a global variable rather than a local variable. Global variables can be accessed and modified from anywhere in a Python program, whereas local variables are only accessible within the scope where they are defined.

Here’s an example to illustrate the use of the global keyword in Python:

x = 10  # global variable

def my_func():
    global x  # declaring x as a global variable
    x = 5    # modifying the value of x
    print("Inside my_func: x =", x)

my_func()

print("Outside my_func: x =", x)

In this example, we have a global variable x that has a value of 10. We then define a function called my_func which modifies the value of x to 5 using the global keyword. This tells Python that we want to modify the global variable x instead of creating a new local variable.

When we call my_func, the value of x inside the function is changed to 5 and the function prints the value of x inside the function. When we print the value of x outside the function, we can see that it has been modified to 5:

Inside my_func: x = 5
Outside my_func: x = 5

Without using the global keyword inside the function, Python would have created a new local variable x with a value of 5, and the global variable x would not have been modified.

It’s worth noting that the use of global variables can sometimes lead to unexpected behavior and make code harder to understand and maintain. As a best practice, it’s often better to avoid global variables and instead pass values between functions using parameters and return values.

Leave a Reply