Can anyone help me create a codeblock using an if/then statement through the Python parser in Field Calculator, to calculate the length of a line segment when the value of a different field is a certain value?

I am trying to calculate percentages of Passing Zones within Undivided 2-Lane State Highways. I have one field [PassingZoneDesc] with values "Both", "Left", "Right" and "None". I have added fields for each type of Passing Zone, and would like to create an expression in Field Calculator that goes along the lines of If [PassingZoneDesc] = "Left" Then [Length_NPZ_Left] = !Shape.Length@Miles! else [Length_NPZ_Left] = 0.

I understand the above is a messed-up mash of VB Script and Python. Frankly, I am more familiar with VB Script but apparently ArcMap only supports geometry calculations in Field Calculator with Python now (hence the Python length calculation above). I know there are workarounds available, but I'm just wondering if there is a way to calculate the lengths in this manner.

I am not permitted to upload an actual sample of the data, but here is a screenshot of the attribute table and a draft code I was trying to use.

enter image description here

  • You can compute shape length in a separate field and use vb instead of Python. On the other hand simple summary statistics on passing zone and length will do.
    – FelixIP
    Commented Aug 10, 2020 at 21:39
  • I certainly could do as you suggested, but was just wondering if it was even possible to calculate the lengths in the way I specified. Ultimately, yes, it is possible to calculate it with one expression in Field Calculator! See below for user answers. Commented Aug 11, 2020 at 15:09

3 Answers 3


Use the following codeblock and assignment statement.


def reclass(l, d):
    if (d =="Both"):
        return l
        return 0

Assignment statement:

reclass(!Shape.length@Miles!, !PassingZoneDesc!)
  • This worked! Thank you! Commented Aug 11, 2020 at 14:48

I think the expression below will do the job:

!Shape.length@miles! if !PassingZoneDesc! == "Left" else 0

  • With a tiny bit of tweaking, it worked! Thanks! Commented Aug 11, 2020 at 15:03

Per some awesome user answers, there are two options for calculating length with an if/then statement using the Python codeblock in Field Calculator. Below are both calculations that worked for me:

!Shape.Length@Miles! if !PassingZoneDesc! == "Left" else 0

The above one was pasted into the expression line directly (no codeblock needed). The below one utilizes a codeblock and expression.


def reclass(L, d):
    if (d == "Left"):
        return L
        return 0


reclass(!Shape.Length@Miles!, !PassingZoneDesc!)

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.