0

I am getting the error "local variable 'Xold' referenced before assignment". I don't understand why I am getting the error as I have assigned the variable in question before I attempt use it.

def calculator (newX,newY):
    global count
    if  count==0:
        Xold = newX
        Yold = newY
        count+=1
        print(Xold,Yold) #prints 97.9 which is correct. 
    else:
        Xdistance = newX - Xold
        Ydistance = newY - Yold
        print(Xdistance,Ydistance)
        parser()

Just to mention, count is set to 0 at the beginning of the code.

John G
  • 19
  • 2
  • 7
  • Yes, if you enter the else block neither `Xold` not a Yold` are defined. So it will give this error any time `count != 0` – juanpa.arrivillaga Mar 13 '18 at 16:38
  • Hint: All of the variables in a function are thrown away as soon as the function returns (or when execution "falls off the end" of the function). – Kevin Mar 13 '18 at 16:41
  • 1
    Possible duplicate of [UnboundLocalError: local variable ... referenced before assignment](https://stackoverflow.com/questions/4048745/unboundlocalerror-local-variable-referenced-before-assignment) – holdenweb Mar 13 '18 at 16:42
  • The issue is that `Xold` and `Yold` are local, not global, so even if `count` is then, once it is > 0, the error will rise – Vinz Mar 13 '18 at 16:42
  • @Kevin so I need to store the variable elsewhere? I just want to have the initial value from the parser stored in Xold and Yold. – John G Mar 13 '18 at 16:46

1 Answers1

2

Your else guard is executing first, so Xold is not being assigned. Even though Xold appears in a line above, it's in a block that isn't being executed.

The steps as they are executed are:

calculator(x, y)
  if count == 0 # False
  else:
  Xdistance = newX - Xold # Xold is not defined yet

You will need to define it with sensible variables outside the if clause.

If you want to be clever, you can do something like this

count = 0

def calculator (newX,newY):
    global count
    if  count==0:
        calculator.Xold = newX
        calculator.Yold = newY
    count+=1
    print(calculator.Xold,calculator.Yold) #prints 97.9 which is correct. 
else:
    ...
munk
  • 12,340
  • 8
  • 51
  • 71