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

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.

When 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 6.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?