When I calculate a field like this:

arcpy.CalculateField_management("Layer", field_0, '!field_name1! / !field_name2!', "PYTHON_9.3")

It works! The field "field_name0" in the attribute table is populated with the value calculated from fields "field_name1" and "field_name2".

But, if I use variables instead of field names:

arcpy.CalculateField_management("Layer", field_0, 'field_1 / field_2', "PYTHON_9.3")

I get this error:

Runtime error Traceback (most recent call last): File "", line 3, in File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3354, in CalculateField raise e ExecuteError: ERROR 000539: Error running expression: field_1/ field_2 Traceback (most recent call last):
File "", line 1, in NameError: name 'field_1' is not defined Failed to execute (CalculateField).

I want to use loops later on, that's why I want it to work with variables, and not simply with direct field names.


You are missing the wrapping exclamation marks, try this:

arcpy.CalculateField_management("Layer", field_0, '!' + field_1 + '!/!' + field_2 + '!', "PYTHON_9.3")
  • 2
    in the middle, it should be '!/!' and not '/', otherwise your field names are not distinguished – radouxju Oct 20 '14 at 21:41

Based on your variable, you just need to make sure variables and strings are not confused


arcpy.CalculateField_management("Layer", field_0, field_1 + " / " + field_2, "PYTHON_9.3")

note that if you have the strings as variables without the "!", it is nicer to use format()


arcpy.CalculateField_management("Layer", field_0, """!{}!/!{}!""".format(field_1,field_2), "PYTHON")

You have embedded the string variable within a string so python sees it as a string.

I would suggest you make you code something like:

calcString = "!field_name1! / !field_name2!"
arcpy.CalculateField_management("Layer", field_0, calcString', "PYTHON_9.3")
  • 2
    I do not think the calcString should be hard coded, reference variables instead. – artwork21 Oct 20 '14 at 20:51

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.