I'm writing a python program where I need to field calculate using a python function. The function takes two strings; one used for an if statement and the other to become an integer complete a simple addition equation. It then returns a string of that integer.

I've completed the calculation on the table in ArcCatalog and it works, but in Python it doesn't and gives me the following error:

ExecuteError: Failed to execute. Parameters are not valid. ERROR 000989: Python syntax error: Parsing error SyntaxError: invalid syntax (line 1) Failed to execute (CalculateField).

My function:

def yearStr(age, date):
    if age == 'BC':
         start = str((int(date) * (-1)) + 2251)
    if age == 'AD':
        start = str(int(date) + 2251)
    return start

Called using this:

yearStr(!Period!, !Year!)

In Python it looks like this:

arcpy.CalculateField_management(transp_table,"Start_Time","yearStr(!Period!, !Year!)","PYTHON_9.3","def yearStr(age, date):/n  if age == 'BC':/n    start = str((int(date) * (-1)) + 2251)/n  if age == 'AD':/n    start = str(int(date) + 2251)/n  return start")

I would appreciate any help! Have tried adding ' ' around field names and variables

  • Are you trying to update a shapefile or a geodatabase feature class?
    – Fezter
    Commented Aug 2, 2013 at 5:30

2 Answers 2


You can use something like that:

expression = "yearStr(!Period!, !Year!)"

codeblock = """yearStr(age, date):
    if age == 'BC':
         start = str((int(date) * (-1)) + 2251)
    if age == 'AD':
        start = str(int(date) + 2251)
    return start"""

and then use:

arcpy.CalculateField_management(transp_table,"Start_Time", expression, "PYTHON", codeblock)
  • This is still giving me the same issues as I mentioned above
    – parnelandr
    Commented Aug 2, 2013 at 0:08

It's actually quite simple why your code isn't working. Whenever you use Copy Python Snippet, newline characters are copied as /n and not \n. Assuming everything else is syntactically correct, changing the forward slashes to back slashes will make it work.

It's also a lot easier to format your codeblock like @ConeGIS is doing. It's a lot easier to read, write, and debug code.

If you positive that age can only be BC or AD (there can be no blank cells), then the following should be slightly faster.

codeblock = """yearStr(age, date):
    return str(-int(date) + 2251) if age == 'BC' else str(int(date) + 2251)"""

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.