Select to view content in your preferred language

Using Conditional Statements to add from different fields in Field Calculator (Python)

1124
3
Jump to solution
02-24-2021 09:04 AM
Labels (1)
JoshBillings
Frequent Contributor

Hey all,

I am new to Python. I am currently trying to write a calculation using Python in the field calculator ONLY IF another field equals a specific value.

For instance, I have a MAINTENANCECOMPLETE field, a MAINTENANCETYPE field, a DEFMAINTENANCE field, and a COST field.

I want the MAINTENANCECOMPLETE field to populate the sum of DEFMAINTENANCE and COST only if MAINTENANCETYPE is equal to "DM General."

Here is what I currently have:

Code Block:

def ifBlock(maintenanceType):
     if maintenanceType== 'DM General'
          return !DEFMAINTENANCE! - !Cost!

 

Actual Code:

ifBlock(!MaintenanceType!)

 

How should I write this differently?

Let me know if I can clarify in any way.

 

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

You don't have to use the code block for this, you can use Python conditional expression, a.k.a, ternary operator:  6. Expressions — Python 3.9.2 documentation

Expression:

!DEFMAINTENANCE! + !COST! if !MAINTENANCETYPE! == 'DM General' else !MAINTENANCECOMPLETE!

View solution in original post

3 Replies
JoshuaBixby
MVP Esteemed Contributor

You don't have to use the code block for this, you can use Python conditional expression, a.k.a, ternary operator:  6. Expressions — Python 3.9.2 documentation

Expression:

!DEFMAINTENANCE! + !COST! if !MAINTENANCETYPE! == 'DM General' else !MAINTENANCECOMPLETE!
JoshBillings
Frequent Contributor

Genius. Thank you. I was making it more difficult than I should have.

What if I had several attributes for MAINTENANCETYPE?

When I try to use this below, it populates all fields with the difference of DEFMAINTENANCE - COST even if it doesn't meet the criteria:

!DEFMAINTENANCE! - !COST! if !MAINTENANCETYPE! == 'DM General' or 'DM Asset Protection' or 'DM Priority Safety Concern' else !MAINTENANCECOMPLETE!

 

Any way to do this @JoshuaBixby ?

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

This should work:

!DEFMAINTENANCE! - !COST! if !MAINTENANCETYPE! in ('DM General','DM Asset Protection','DM Priority Safety Concern') else !MAINTENANCECOMPLETE!