Python global variables do not conform to the relevant rules of parameter passing, so many people do not want to use them frequently unless constants are defined. We will discuss global variables and find the hidden tips. I hope you will gain some gains through this article.
The program is roughly like this:
- CONSTANT = 0
-
- def modifyConstant() :
- print CONSTANT
- CONSTANT += 1
- return
-
- if __name__ == '__main__' :
- modifyConstant()
- print CONSTANT
-
The running result is as follows:
UnboundLocalError: local variable 'constant' referenced before assignment: Why does the Python global variable become a local variable in the modifyConstant function?
Modify:
- CONSTANT = 0
-
- def modifyConstant() :
- print CONSTANT
- #CONSTANT += 1
- return
-
- if __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 I access and modify Python global variables inside the function? The keyword global should be used to modify variables a bit like PHP ):
- CONSTANT = 0
-
- def modifyConstant() :
- global CONSTANT
- print CONSTANT
- CONSTANT += 1
- return
-
- if __name__ == '__main__' :
- modifyConstant()
- print CONSTANT
-
If you have any questions about the solution, you may wish to take a look at the above solutions to better understand it and ensure smooth application in practical applications.