In Python, you can declare global variables using the global keyword.

Variables declared as global inside a function using the keyword ‘global’ will be marked as global variables, making them accessible and modifiable outside the function.

The code example is shown below:

def my_function():
    global x
    x = 10

my_function()
print(x)  # 输出:10

In the above example, the function my_function() uses global x to declare the variable x as a global variable and assigns it a value of 10. When print(x) is called outside the function, it can output the value of the global variable correctly.

bannerAds