Sobes.tech
Junior

Why is it necessary to use the 'global' keyword in Python?

sobes.tech AI

Answer from AI

The keyword global is used to modify a variable that is in the global scope from within a local scope (for example, inside a function). Without global, attempting to assign a value to a variable inside a function will create a new local variable with the same name, and the global variable will remain unchanged.

x = 10  # Global variable

def modify_local():
    x = 5  # Create a new local variable x
    print(f"Inside function (local): {x}")

def modify_global():
    global x  # Indicate that we want to work with the global variable x
    x = 5  # Change the global variable x
    print(f"Inside function (global): {x}")

print(f"Initially: {x}")
modify_local()
print(f"After modify_local: {x}")  # Global x remains unchanged
modify_global()
print(f"After modify_global: {x}")  # Global x has changed

The global keyword should be used with caution, as frequent modification of global variables from functions can make debugging and understanding the code more difficult. Generally, it is preferable to pass variables to functions as arguments and return the modified values.