When defining a function in Python, if you want to operate on variables outside the function inside the function, you need to declare it as global inside the function.
Example 1
x = 1
def func():
x = 2
func()
print(x)
输出:1
In the func function, global is not added in front of x, so the func function cannot assign x to 2, and cannot change the value of x
Example 2
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
x = 1
def func():
global x
x = 2
func()
print(x)
输出:2
With the addition of global, you can operate on objects outside the function inside the function, and you can also change its value
Example 3
global x
x = 1
def func():
x = 2
func()
print(x)
输出:1
Global needs to be declared inside the function, if it is declared outside the function, the function still cannot be operated