0

I am trying to give polygons values in a layer based on the sum population within other adjacent polygons. The polygons are adjacent as I have already sorted them through the appropriate field. This is my code:

def CreatePolls(DB_ID, pop):
    for i in DB_ID:
        SumPop = 0
        PollCount = 1        
        SumPop += pop
        if SumPop < 500:
            return PollCount
        elif SumPop > 500:
            return PollCount
            PollCount += 1
            SumPop = 0
arcpy.CalculateField_management('DB_Test', 'Poll_Div', CreatePolls("!DB_ID!","!Population!"))

When I try to run it I get the following errors:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 5, in CreatePolls
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

Any ideas?

3
  • SumPop += "!Population!". You can't actually call CreatePolls from within your python code. You need to write the code block as a string and pass that into CalculateField, as seen in the examples: pro.arcgis.com/en/pro-app/2.8/tool-reference/data-management/…
    – mikewatt
    Commented Aug 12, 2022 at 17:08
  • That worked mikewatt. Thanks! Now I got to figure out why PollCount is not increasing by 1 haha! Commented Aug 12, 2022 at 17:34
  • There is no increment because you don't have an increment anywhere in the viable code path (the lines after a return at the same indent level will never be executed).
    – Vince
    Commented Aug 12, 2022 at 18:32

1 Answer 1

1

As your SumPop variable =0, we know with certainty this is an int. Your pop variable is whatever your !Population! field is. Based on the error, this field appears to be a str

You'll need to verify in your data that your Population field is actually a float or double. Alternatively, you can try to cheat and cast the field as an int. I say cheat because if you have actual string values in here, like "a", this won't work.

SumPop += int(pop)

1
  • I tried your method and it didn't work. I even converted the Population field to double just to be sure. Commented Aug 12, 2022 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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