In Python, a global variable is a variable that is defined outside of a function and can be accessed from anywhere in the code. Here is an example of how to define and access a global variable:
x = 10 # Global variable def foo(): print(x) foo() # Output: 10
You can also modify the value of a global variable inside a function, but you must use the
global keyword to tell Python that you want to modify the global variable, rather than creating a new local variable with the same name. Here is an example:
x = 10 # Global variable def foo(): global x x = 20 foo() print(x) # Output: 20
It is generally considered good practice to avoid using global variables, as they can make it difficult to understand the flow of data in a program and can lead to conflicts if different parts of the code modify the same global variable. Instead, it is usually better to pass values to functions as arguments and return values from functions as needed.
def foo(x): x = x + 10 return x x = 10 x = foo(x) print(x) # Output: 20