The scope of global and nonlocal in python

The order of python reference variables: current scope local variables -> outer scope variables -> global variables in the current module -> python built-in variables.

A global
keyword is used to use global variables in functions or other local scopes. But you can also not use the global keyword if you don't modify global variables.
1 gcount = 0
2
3 def global_test():
4 gcount+=1
5 print (gcount)
6 global_test()
UnboundLocalError: local variable 'gcount' referenced before assignment
If you want to modify the global variable in the function, you need to use the keyword global

2. Declare a global variable. If you want to modify the global variable locally, you need to declare the global variable locally:

gcount = 0

def global_test():
global gcount
gcount+=1
print (gcount)
global_test()
If gcount is declared as a global variable in the function, it can be modified. correctly outputs 1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325230981&siteId=291194637