0

I'm trying to do something along the following lines in python3:

i = 1337
def g():
    print(i)
    i = 42
g()

but get the following error

UnboundLocalError: local variable 'i' referenced before assignment

I think I understand what the error message means, but why is it the case? Is there any way to circumvent this?

Konstantin Weitz
  • 6,180
  • 8
  • 26
  • 43

3 Answers3

5

In two words - when a given variable name is not assigned a value within a function then references to the variable will be looked up. Use global - and in such a case python will look for i in global scope:

i = 1337

def g():
    global i
    print i
    i = 42

g()

You can read more on variable scopes in PEP-0227

Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
1

If you really really want to do it that way, you'll need to get i from the global scope.

def g():
    global i
    print i
    i = 42

However, generally you would be much better off changing how your code works to not require globals. Depending on how you are using it, that could be as simple as passing in i as a parameter and returning the changed value.

Collin Green
  • 2,146
  • 14
  • 12
0

An example of Keeyai's suggestion of passing in i as a parameter:

i = 1337
def g(i):
    print(i)
    i = 42
g(i)

However, you never use the new value of i, so perhaps something like this makes more sense:

def g (i):
    i = 42
    return i

i = 1337
print g(i)
btanaka
  • 382
  • 2
  • 6