Main Content

UnboundLocalError - Python Message

Archive - Originally posted on "The Horse's Mouth" - 2009-01-31 06:09:48 - Graham Ellis

What does THIS mean?

UnboundLocalError: local variable 'taxrate' referenced before assignment

It means that you have tried to modify the value of a variable - perhaps in a function - before you have given it an initial value:

taxrate = 15
def getnet(gross):
  taxrate /= 100.
  net = gross - gross / (1.0 + taxrate)
  return net
amount = getnet (230)
print amount


The variable taxrate is local to the getnet function ... the way the code is written, there is a DIFFERENT taxrate variable in the calling code.

You could share the variable by declaring it global in the function or - much better - you could use it read only in the function, in which case Python will see it from the outer scope.

So this will work:

taxrate = 15
def getnet(gross):
  net = gross - gross / (1.0 + taxrate/100.0)
  return net
amount = getnet (230)
print amount


And that's also far better because it doesn't alter the variable that contains the tax rate - rather it leaves it available for later use.