2

I've been creating a series of random events where each function does something different to a main set of variables, yet I keep getting unbound local errors. Here's a watered down version of the barebones of my code

  variable = 1

  def main():
     global variable
     secondary()
     variable = secondary()

 def secondary()
    variable += 1
    return variable

once again this is a really minimal way to explain my code but the variable += 1 is the part that is expressing the error

Riley M
  • 41
  • 2

2 Answers2

4

I noted all of the same issues that @TimothyChen mentioned. I'd like to explain the error you're asking about, which is:

UnboundLocalError: local variable 'v' referenced before assignment

That happens here:

v = 1

def secondary()
    v += 1

The issue here is due to a behavior that is unique to Python, and a little strange (please excuse that I changed the name variable to v to avoid confusion)...

If there is a global variable declared named v, and then you only read from a variable named v inside a function, Python declares that you are reading from the global variable named v.

If there is a global variable declared named v, and then you write to a variable named v inside a function, Python says that that's a different variable local to the function unless you first say global v in that function, after which point v refers to the global variable.

So the case of your function secondary(), you are A) writing to v in the function, and B) you don't say global v anywhere in the function. So Python says that inside that function, v is a unique variable local to that function. But if v is local to the function, and your first reference to the variable in that function is:

v += 1

then v hasn't been assigned a value prior to this point. Since this line of code first reads from v, and then writes a new value back to it, you get the error you're seeing because of the attempt to read from a variable that hasn't yet been assigned a value.

It seems pretty clear that what you need to do to fix this issue is to declare your secondary function as follows:

def secondary()
    global variable
    variable += 1
    return variable

The addition of global variable tells Python that your reference to variable is referring to the global variable with that name, even though you are writing to it.

I would suggest that in the future, you not name variables variable. That can only lead to confusion.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
1

In the secondary function, variable isn't defined. You would have to do global variable, which would make the variable accessible. Also, you call secondary twice, which would make the variable go up twice, not sure you would want that. Furthermore, secondary doesn't have a colon after the parentheses which creates a syntax error. Lastly, the code most likely isn't indented correctly, as the secondary variable is not indented, although the other code blocks are.

Timothy Chen
  • 431
  • 3
  • 8