Python global variables

From:

Global variables do not meet the arguments passed to the spirit, so, I rarely use, unless defined constants. A colleague asked about a global problem today, only to find that the original and the doorway.

The program is roughly such:

CONSTANT = 0

def modifyConstant() :

print CONSTANT

CONSTANT += 1

return

if __name__ == ‘__main__’ :

modifyConstant()

print CONSTANT

Results are as follows:

UnboundLocalError: local variable ‘CONSTANT’ referenced before assignment

It seems, global variables in the function modifyConstant in the edge into local variables, it seems no effective global variables?

Do some revision:

CONSTANT = 0

def modifyConstant() :

print CONSTANT

#CONSTANT += 1

return

if __name__ == ‘__main__’ :

modifyConstant()

print CONSTANT

In normal operation, it inside a function can access global variables.

So, the problem is, because inside the function to modify the variables CONSTANT, Python thinks that CONSTANT is a local variable, while print CONSTANT and in CONSTANT + = 1 before, so of course this error occurs.

So, how to modify global variables in the access to the internal function? Should use the global keyword to modify variables (a bit like PHP):

CONSTANT = 0

def modifyConstant() :

global CONSTANT

print CONSTANT

CONSTANT += 1

return

if __name__ == ‘__main__’ :

modifyConstant()

print CONSTANT

So simple!

Posted by Barbara at November 16, 2013 - 7:08 AM