How to Use Global Variables in a Python Function?
Global variables can be used in a Python function by declaring them as global within the function. Here's an example:
x = 5 def myFunc(): global x x += 1 print(x) myFunc() # Output will be 6
In this example, we have a global variable
x assigned to 5. We define a function
myFunc that increments
x by 1 and then prints its value.
Within the function, we declare
x as global using the
global keyword. This allows us to access the global variable
x and modify its value within the function.
myFunc() is called, it increments
x by 1 (so
x now has a value of 6) and then prints it out. The output from this code will be