Python Global Keyword
In Python, the global
keyword is used to declare a variable in a function as a global variable. When a variable is declared as global within a function, it can be accessed and modified from outside the function as well.
Here's an example that demonstrates the use of the global
keyword:
x = 10 # global variable def foo(): global x # declare x as a global variable x = 20 # modify the global variable inside the function foo() # call the function print(x) # Output: 20 (global variable modified by the function)
In this example, we define a global variable x
with a value of 10
. We define a function foo()
that modifies the global variable x
using the global
keyword. When we call the function and print the value of x
, we can see that the global variable has been modified by the function.
It's important to note that if a variable is not declared as global within a function, Python will create a new local variable with the same name, which will shadow the global variable. Therefore, if you want to modify a global variable inside a function, you must use the global
keyword to declare it as a global variable.