Can anyone explain what I've done wrong here. Have a feeling this is really simple...(new to Python). This code si being pasted into the Immediate window in ArcMap 10.1, in order to calculate a field with an "incrementing" value. I would like to specify the starting value externally.
Thanks!
This works:
arcpy.CalculateField_management("xx4_ncard","as_drv_srt","autoIncrement()","PYTHON_9.3","rec=0\ndef autoIncrement():\n global rec\n pStart = 1 #adjust start value, if req'd \n pInterval = 1 #adjust interval value, if req'd\n if (rec == 0): \n rec = pStart \n else: \n rec = rec + pInterval \n return rec")
This doesn't:
start = 1
arcpy.CalculateField_management("xx4_ncard","as_drv_srt","autoIncrement()","PYTHON_9.3","rec=0\ndef autoIncrement():\n global rec\n pStart = " + start + " #adjust start value, if req'd \n pInterval = 1 #adjust interval value, if req'd\n if (rec == 0): \n rec = pStart \n else: \n rec = rec + pInterval \n return rec")
Solved! Go to Solution.
You can't concatenate a string and a number. Convert the number to a string before concatenating: str(start)
You can't concatenate a string and a number. Convert the number to a string before concatenating: str(start)
Thanks for the quick reply - the code now works as expected.
For future reference, please mark questions as questions, instead of discussions.
I converted to question (Actions menu, upper right) and gave Darren his deserved cookie.
Keith, I know you're new to Python but have to mention this: the CalculateField tool is great in Desktop and ModelBuilder, but in many cases update cursors are FAR easier for this kind of thing in scripting:
To wit:
val = 0
inc = 1
with arcpy.da.UpdateCursor("xx4_ncard", "as_drv_srt") as rows:
for row in rows:
row[0] = val
val += inc
rows.updateRow()