« Python - a truly dynamic language | Main | Baby Caleb and Fortune City in your web logs? »

January 31, 2009

UnboundLocalError - Python Message

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.

Posted by gje at January 31, 2009 06:09 AM

Comments

Well House Consultants Ltd. Copyright 2010