The examples in this article describe Python global variable usage. Share to everyone for your reference, specific as follows:
Global variables do not conform to the spirit of parameter passing, so I rarely use them unless we define constants. Today, a colleague asked a question about the global variable, only to find that there was a doorway.
The program is roughly like this:
CONSTANT = 0
def modifyconstant ():
print CONSTANT
CONSTANT + + 1 return
if __name__ = ' __main__ ':
modifyconstant ()
print CONSTANT
The results of the operation are as follows:
Unboundlocalerror:local variable ' CONSTANT ' referenced before assignment
It seems that the global variable in the function Modifyconstant edge into a local variable, it seems that the global variable does not take effect?
Make some changes:
CONSTANT = 0
def modifyconstant ():
print CONSTANT
#constant + + 1 return
if __name__ = ' __main __ ':
modifyconstant ()
print CONSTANT
Functioning normally, it seems that the function is internally accessible to global variables.
So, the problem is, because the variable Constant,python inside the function is considered constant is a local variable, and print constant is 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 variables (a bit like PHP):
CONSTANT = 0
def modifyconstant ():
global CONSTANT
print CONSTANT
CONSTANT + = 1 return
if __ name__ = = ' __main__ ':
modifyconstant ()
print CONSTANT
It's that simple!
More information about Python-related content can be viewed in this site: "Python file and directory operation tips Summary", "Python Picture Operation skills Summary", "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", " Python function Usage Tips Summary, python string manipulation tips, Python code manipulation tips and Python introductory and advanced classic tutorials
I hope this article will help you with Python programming.