0

I made a Python script tool and to finish my script I want to perform a percentage calculation using the 2 results from my search cursors. And the print the result to screen.

Here's what I have (but not working):

# Run search cursor on areas with slope code 3
with arcpy.da.SearchCursor(shapecalc_input, ['POLY_AREA'], "SlopeCode in (3)") as cur1:
     sum = 0    
     for row in cur1:     
       sum += row[0]    

arcpy.AddMessage(sum)

# Run search cursor on areas with slope code 1 and 2
with arcpy.da.SearchCursor(shapecalc_input, ['POLY_AREA'], "SlopeCode in (1, 2)") as cur2:
     sum = 0    
     for row in cur2:     
       sum += row[0]    

arcpy.AddMessage(sum)

arcpy.AddMessage((cur1/cur2)*100)

My search cursors give me the right values, just the calculation isn't working (last line).

Is my syntax wrong? or should I be using a different method completely? I'm new to Python.

  • 2
    Next time, please don't tell us your code "isn't working". Tell us exactly what happens, particularly the full exception text if an error is raised. – user2856 Nov 25 '16 at 0:59
2

You are overwriting the sum variable with your 2nd cursor which you should be using to calculate the percent, not the cursors.

Use:

# Run search cursor on areas with slope code 3
with arcpy.da.SearchCursor(shapecalc_input, ['POLY_AREA'], "SlopeCode in (3)") as cur1:
     sum1 = 0    
     for row in cur1:     
         sum1 += row[0]    

# Run search cursor on areas with slope code 1 and 2
with arcpy.da.SearchCursor(shapecalc_input, ['POLY_AREA'], "SlopeCode in (1, 2)") as cur2:
     sum2 = 0    
     for row in cur2:     
         sum2 += row[0]    

arcpy.AddMessage((sum1/sum2)*100)

Or with a single cursor:

# Run search cursor on areas with slope code 1, 2 or 3
with arcpy.da.SearchCursor(shapecalc_input, ['POLY_AREA', 'SlopeCode'], "SlopeCode in (1, 2, 3)") as cur:
     sum1 = sum2 = 0    
     for row in cur:     
         if row[1] == 3:
             sum1 += row[0]
         else:
             sum2 += row[0]

arcpy.AddMessage((sum1/sum2)*100)

One note: it would be simpler to leave your slope classification in raster to calculate the area.

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.