I am trying to add a field with incremental ID for a shapefile with certain feature classes. I know this can be done by using Sort tool and then use the Add Incremental ID field tool. But since I'm learning Python, and this seems like not too difficult a problem to tackle with Python, I want to use Python to handle this to enhance my Python skills.

Below is the code I put in the Code Block:

def letsdothis():
    rec = 0
    vStart = 1
    vDelta = 1
    if rec == 0:
        rec += vStart
        rec += vDelta
    return rec

And the function I use of course is letsdothis()

To show it better:


My reasoning is this:

The first one will be rec += 1, then rec will equal 1. Then the next one, since rec != 0. it will be (the new rec value) += 1, which will be 2. And so on and so on.

But the results are all 1. My understanding is that for every row cell/feature class, the function will be called from scratch therefore rec will equal 0 instead hold the value that's calculated in the previous feature class/row.

Is this the problem with my code? I am very new to writing my own Python code in GIS. I've only used other's code and tweaked them to fit my purpose before so I don't know how to really do this.

Rec Pass on

If I can make rec == 1 in the first row, how shall I make that value pass on to the nest row?

1 Answer 1


This is a def variable scope related confusion that you have. Basically each and every row calculation creates an instance of your def and its rec value is always 0! Therefore you should control its incremental behaviour outside of the def.

The original code puts rec variable outside of the def and declares rec as global inside the def. Check the first part of the answer of this post out.

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.