I'm using If/else statement to calculate geometry (field "LENGTH") for features meeting special criteria (the value in "TYPE" field does not equal AB201, AB202, AB203, AB204, AB205, AB206). The code is: Expression box:


Code Block

def mycalc(TYPE,LENGTH):
    if TYPE != 'AB201' or TYPE != 'AB202' or TYPE != 'AB203' or TYPE != 'AB204' or TYPE != 'AB205' or TYPE != 'AB206': 
        return (!shape.length!/1000)
        return LENGTH

So, I get the error

enter image description here

The command !shape.length! calculates geometry in units of the features' coordinate system, which is 'meter' in my case, so I divide it by 1000 (I need kilometers).

I know I can solve this problem by filtering featureclasses or by calculating selected features. But I use this expression in ModelBuilder, which iterates through a file geodatabase.

How should I change my code?


1 Answer 1


You are not passing in the geometry into the function which is causing the invalid syntax error. So taking on the excellent advice from @BERA it should be:

def myCalc(myTYPE, LENGTH, geom):
    if myTYPE not in ('AB201', 'AB202', 'AB203', 'AB204', 'AB205','AB206'): 
        return (geom.length / 1000)
        return LENGTH
  • many thanks! It works!
    – Vadim
    Dec 14, 2021 at 14:27

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.