Global variables do not conform to the spirit of parameter passing. Therefore, I seldom use them unless a constant is defined. Today, when a colleague asked a question about global variables, he found that there were still internal global variables that do not conform to the spirit of parameter transfer. Therefore, I rarely use them unless I define constants. 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