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.
Solved! Go to Solution.
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!
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!
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 ?
This should work:
!DEFMAINTENANCE! - !COST! if !MAINTENANCETYPE! in ('DM General','DM Asset Protection','DM Priority Safety Concern') else !MAINTENANCECOMPLETE!