How do you define global variables in Python?

In Python, you can use the global keyword to define global variables.

For example, the variable x in the following example is a global variable.

x = 10  # 全局变量

def func():
    global x  # 声明x是全局变量
    x = 20  # 修改全局变量的值

func()
print(x)  # 输出:20

After declaring the global keyword within a function, the value of a global variable can be directly modified. The global keyword declaration is not needed when using global variables outside of a function.

Leave a Reply 0

Your email address will not be published. Required fields are marked *