163
test1 = 0
def test_func():
    test1 += 1
test_func()

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 test_func?

Neuron
  • 5,141
  • 5
  • 38
  • 59
foxneSs
  • 2,259
  • 3
  • 18
  • 21
  • 12
    It is local, because you assign to it within the function. – Daniel Roseman Aug 10 '12 at 15:41
  • 2
    I received the same error but in my case it turned out to be an indentation problem. The code I was modifying was indented with spaces, but my editor was indenting with tabs. Dumb mistake on my part, and not at all the problem you had, but I hope to save someone out there some time by commenting here -- this was the first hit in my Google search. – Josh Aug 15 '17 at 19:19

3 Answers3

282

In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

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

However, if you only need to read the global variable you can print it without using the keyword global, like so:

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

But whenever you need to modify a global variable you must use the keyword global.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Florin Stingaciu
  • 8,085
  • 2
  • 24
  • 45
64

Best solution: Don't use globals

>>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1
jamylak
  • 128,818
  • 30
  • 231
  • 230
12

You have to specify that test1 is global:

test1 = 0
def test_func():
    global test1
    test1 += 1
test_func()
Neuron
  • 5,141
  • 5
  • 38
  • 59
Stanislav Heller
  • 551
  • 2
  • 10