The global keyword in Python
The global keyword is used to declare that a variable is a global variable and should be accessed from the global scope. This is useful when we want to modify a global variable from within a function.
Example:
Python
x = 10 # global variable # Create a function def my_function(): global x x = 5 # this will change the value of the global variable x y = 5 # local variable print(x) # prints 10 # Call a function my_function() # Print the variable print(x) # prints 5 print(y) # this will cause an error because y is a local variable and is not accessible outside of the function
In this example, we used the global keyword to declare that we want to modify the global variable x from within the function. As a result, the value of x is changed to 5.
It's important to note that it's generally considered good practice to avoid modifying global variables from within functions, as it can lead to unexpected behavior and make our code harder to debug.