In Python, the global keyword is used to declare a variable as global, which means it can be accessed and modified from any part of the program.
When a variable is defined inside a function, it is considered local to that function and can only be accessed within the function. However, by using the global keyword, we can access and modify the global variable inside the function. Here's an example:
x = 5def add_to_x(y): global x x += yadd_to_x(3)print(x) |
In this example, we define a global variable x with a value of 5. We then define the add_to_x function that takes an argument y and uses the global keyword to declare x as a global variable inside the function. We then modify x by adding y to it.
Finally, we call the add_to_x function with an argument of 3 and print the value of x, which is now 8.
Note that the use of the global keyword should be used with caution, as it can make debugging and maintaining code more difficult. It's generally considered best practice to avoid using global variables and instead use local variables or pass values between functions as arguments and return values.