Select to view content in your preferred language

including Python variable in codeblock

1481
4
Jump to solution
09-22-2016 04:22 PM
KeithD1
Occasional Contributor

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")
0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

You can't concatenate a string and a number. Convert the number to a string before concatenating: str(start)

View solution in original post

4 Replies
DarrenWiens2
MVP Honored Contributor

You can't concatenate a string and a number. Convert the number to a string before concatenating: str(start)

KeithD1
Occasional Contributor

Thanks for the quick reply - the code now works as expected.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

For future reference, please mark questions as questions, instead of discussions.

0 Kudos
curtvprice
MVP Esteemed Contributor

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()‍‍‍‍‍‍‍
0 Kudos