How to define global variables in Python?

In Python, you can use the “global” keyword to define global variables, which are accessible throughout the entire program.

Here is an example of defining global variables:

def my_function():
    global my_variable  # 声明my_variable为全局变量
    my_variable = 10

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

In the example above, my_variable is declared as a global variable and assigned a value in the my_function function. Outside the function, the my_variable variable can be accessed and used directly.

bannerAds