How to define global variables in Python

In Python, you can use the “global” keyword to define global variables within a function. Global variables are variables defined outside of a function and can be used anywhere in the program.

Here is an example of how to define global variables in Python:

global_var = 10  # 在函数外部定义的全局变量

def my_function():
    global global_var  # 声明global_var为全局变量
    global_var = 20  # 修改全局变量的值
    print(global_var)  # 输出全局变量的值

my_function()  # 调用函数
print(global_var)  # 输出全局变量的值

In this example, global_var is a global variable defined outside the function. Inside the function my_function, global_var is declared as a global variable using the global keyword, allowing its value to be modified. After calling my_function, the value of the global variable will be changed to 20 and outputted outside the function.

bannerAds