1

I'm trying to use an if statement in the field calculator: This is what the code looks like in Python:

a= 2 
FacilityID= !FACILITYID! 
if a%2==0:
   MH_ID_Calc=FacilityID[0:6]
else:
   MH_ID_Calc=FacilityID[7:14]

print MH_ID_Calc

06M244

so I tried to run that in ArcGIS field calculator:

def myCalc(FID,FACID):
if FID%2==0:
return FACID[0:6]
else:
return FACID[7:14]



myCalc( !FID! !FACILITYID!)

But it fails each time.

Midavalo
  • 29,696
  • 10
  • 48
  • 104
LEECCC
  • 11
  • 1
  • Welcome to GIS SE! As a new user please take the [tour] to learn about our focused Question and Answer format. Please check your indentation - there are no indents in your field calculator code above, but python needs the indents. Also double-check that you've selected the Python Parser in field calculator. – Midavalo Feb 01 '17 at 20:52
  • 1
    What happens when you run the field calculator? There should be result messages under Geoprocessing > Results – Midavalo Feb 01 '17 at 20:53
  • Check out this question and answer which probably makes this a duplicate. – mkennedy Feb 01 '17 at 21:18
  • 3
    myCalc(!FID!, !FACILITYID!)? There's a comma missing when you call the function – Bjorn Feb 01 '17 at 21:43
  • Please edit your question to include the error message. – Aaron Feb 01 '17 at 22:33
  • @LEECCC Your indentation is wrong in your Field Calculator snippet, and you are missing a comma in the expression myCalc(!FID!, !FACILITYID!) - If you fix these, do you still get an error? If so please [edit] your question to include the error message – Midavalo Mar 31 '17 at 00:34

1 Answers1

1

As others have already commented, the parameters of the function call in your expression should be comma separated:

myCalc(!FID!, !FACILITYID!)

And you must use correct indentation with Python (unlike other languages, this is part of Python syntax, and it will not work if the indentation is not correct):

def myCalc(FID,FACID):
    if FID%2==0:
        return FACID[0:6]
    else:
        return FACID[7:14]

Ie, anywhere that a line ends with a colon (:) represents a new code block and the next line should be indented further. All lines within a block must have exactly the same indentation, unless they are part of a sub-block, in which case, they must have the exact same indentation as the other lines a the same level of that sub-block.

Son of a Beach
  • 8,182
  • 1
  • 17
  • 33