This example describes the Python global variable usage. Share to everyone for your reference, as follows:
Global variables do not conform to the spirit of parameter passing, so, usually I seldom use unless I define constants. Today, a colleague asked a question about global variables and found that there were doorways.
The procedure is broadly like this:
CONSTANT = 0def modifyconstant (): print CONSTANT CONSTANT + = 1 returnif __name__ = = ' __main__ ': modifyc Onstant () print CONSTANT
The results of the operation are as follows:
Unboundlocalerror:local variable ' CONSTANT ' referenced before assignment
It appears that the global variable is a local variable in the function modifyconstant, and it seems that the global variable is not in effect?
Make some changes:
CONSTANT = 0def modifyconstant (): print CONSTANT #constant + = 1 returnif __name__ = = ' __main__ ': Modify Constant () print Constant
Running normally, it seems that the function can access the global variables inside.
So, the problem is, because the variable Constant,python inside the function thinks constant is a local variable, and the print constant is before constant + = 1, so of course this error occurs.
So how do you access and modify global variables inside a 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__ = = ' __m Ain__ ': modifyconstant () print CONSTANT
It's so easy!
More interested in Python related content readers can view this site topic: "Python Picture Operation skills Summary", "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", "Python function Use Tips", " Python string manipulation Tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory operations tips
I hope this article is helpful for Python program design.