I have following simple function to get percent values for different cover types from a raster. It gives me following error: UnboundLocalError: local variable 'a' referenced before assignment

which isn't clear to me. Any suggestions?

def percent(ras):
    temp = arcpy.SearchCursor(ras,"","","Value;Count","")
    for row in temp:
        theval = row.getValue("Value")
        thecount = row.getValue("Count")
        if row.getValue("Value") == 1:
            a = thecount
        if row.getValue("Value") == 2:
            b = thecount
        if row.getValue("Value") == 3:
            c = thecount
        if row.getValue("Value") == 4:
            d = thecount
    return a,b,c,d
  • 1
    Because if row.getValue("Value") == 1 might be false and so a never gets assigned. – Nathan W May 20 '13 at 2:39
  • It has value and do gets assigned. I checked it in arcmap interactive python window but can't get it to work in a stand alone script. – Ibe May 20 '13 at 2:44
  • 1
    your loop will also only give you the values of the last loop iteration as you are returning out of the loop and not doing anything with each value. – Nathan W May 20 '13 at 2:49
  • You could use 3 x elif and an else to see if any values other than 1-4 are encountered. – PolyGeo May 20 '13 at 3:44
  • I tried that way as well but still hung up with error. – Ibe May 20 '13 at 4:15

This error is pretty much explained here and it helped me to get assignments and return values for all variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.