foxneSs foxneSs - 1 month ago 18
Python Question

Local (?) variable referenced before assignment


Possible Duplicate:

local var referenced before assignment

Python 3: UnboundLocalError: local variable referenced before assignment




test1 = 0
def testFunc():
test1 += 1
testFunc()


I am receiving the following error:


UnboundLocalError: local variable 'test1' referenced before assignment.


Error says that
'test1'
is local variable but i thought that this variable is global

So is it global or local and how to solve this error without passing global
test1
as argument to
testFunc
?

Answer

In order for you to modify test1 you need to do the following:

test1 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()

If you only needed to read that global varaible you could have just printed it without using the keyword global as so:

test1 = 0
def testFunc():
     print test1 
testFunc()

But whenever you need to modify a global variable you have let python know using the reserved keyword global