Local (?) Variable referenced before assignment

Possible duplicate:
local variable specified before assignment
Python 3: UnboundLocalError: local variable specified before assignment

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

I get the following error:

UnboundLocalError: local variable 'test1' specified before assignment.

The error says that 'test1' is a local variable, but I thought this variable was global

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

+64
python
Aug 10 2018-12-12T00:
source share
3 answers

To change test1 inside the function, you will need to define test1 as a global variable, for example:

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

However, if you only need to read the global variable, you can print it without using the global , for example:

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

But whenever you need to change a global variable, you should use the global .

+109
Aug 10 2018-12-12T00:
source share

Best solution: do not use global s

 >>> test1 = 0 >>> def test_func(x): return x + 1 >>> test1 = test_func(test1) >>> test1 1 
+27
Aug 10 2018-12-12T00:
source share

You must indicate that test1 is global:

 test1 = 0 def testFunc(): global test1 test1 += 1 testFunc() 
+5
Aug 10 2018-12-12T00:
source share



All Articles