In Python, a global variable can be modified inside a function by using the global keyword. This keyword tells the function that you want to use the global variable defined outside the function, rather than creating a new local variable with the same name.
Here’s an example:
# Define a global variable
global_var = 0
def update_global_variable():
global global_var # Declare that we are using the global variable
global_var = 10 # Modify the global variable
print("Global variable inside function:", global_var)
# Call the function to update the global variable
update_global_variable()
# Print the global variable outside the function
print("Global variable outside function:", global_var)
In this example, the update_global_variable function modifies the global_var variable, and the change is reflected outside the function as well.
