What is the meaning of ‘global’ in Python?

In Python, the global keyword is used to declare a variable as a global variable, meaning that the variable can be accessed both inside and outside a function. To use a global variable within a function and modify it, the global keyword must be used to declare it.

When a variable with the same name is defined inside a function, it is treated as a local variable instead of a global variable. Therefore, if you need to modify the value of a global variable within a function, you need to use the ‘global’ keyword.

Here is an example:

x = 10  # 全局变量

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

func()
print(x)  # 输出 20

In the above example, we declared x as a global variable using the global keyword, then modified its value within the function. Lastly, when we printed the value of x outside the function, we obtained the modified global variable value.

bannerAds