This article mainly introduces the usage of global variables in Python, and analyzes the definitions, usage, and precautions of global variables in Python using examples, for more information about global variable usage in Python, see the following example. We will share this with you for your reference. The details are as follows:
Global variables do not conform to the spirit of parameter passing. Therefore, I seldom use them unless a constant is defined. Today, a colleague asked a question about global variables and found that there was still a portal.
The program is roughly like this:
CONSTANT = 0def modifyConstant() : print CONSTANT CONSTANT += 1 returnif __name__ == '__main__' : modifyConstant() print CONSTANT
The running result is as follows:
UnboundLocalError: local variable 'constant' referenced before assignment
It seems that the global variable is a local variable in the modifyConstant function. does it seem that the global variable has not taken effect?
Modify:
CONSTANT = 0def modifyConstant() : print CONSTANT #CONSTANT += 1 returnif __name__ == '__main__' : modifyConstant() print CONSTANT
It seems that the function can access global variables.
Therefore, the problem is that, because the variable CONSTANT is modified inside the function, Python considers CONSTANT as a local variable, and print CONSTANT is before CONSTANT + = 1, this error will certainly occur.
So, how should we access and modify global variables inside the function? You should use the keyword global to modify the variable (a bit like PHP ):
CONSTANT = 0def modifyConstant() : global CONSTANT print CONSTANT CONSTANT += 1 returnif __name__ == '__main__' : modifyConstant() print CONSTANT
That's easy!