# Using IF/ELSE Statement for field calculation in ArcPy?

I would like to calculate the slope value in %, but I don’t want to have any negative values. If there are negative values in the slope field, I would like to multiple them by -1 and if not, multiple them by +1 (or do nothing).

My input is a line shapefile. First I added a field called "slope", then I calculate the slope based on other fields. ``````arcpy.AddField_management(ShapeFileLine, "Slope", "DOUBLE", 10, 3)
arcpy.CalculateField_management(ShapeFileLine, "Slope", '((((!END_Z! - !START_Z!)/!LENGTH_3D!))*100)!',"PYTHON")
``````

What I should do if I want I only have positive values? In this case they are all negatives, but sometimes the positive and negative values are mixed

I agree with @smiller answer about how to do an If Else in a code block.

However, in this particular case, you could also just use the absolute value function which will always return the positive version of a number, regardless if the input is positive or negative https://docs.python.org/2/library/functions.html#abs

Which means it would look something like:

``````arcpy.CalculateField_management(ShapeFileLine, "Slope", 'abs((((!END_Z! - !START_Z!)/!LENGTH_3D!))*100)',"PYTHON")
``````

(FYI: It looked like you had an extra ! at the end of your code block originally, so I removed that because it looked like a miss-type.)

• yes. you are right! I have tested both of the suggestions. they worked.@smiller @John – Anahita Kp Oct 22 '18 at 7:25

Include a codeblock to use if/else.

``````expression = "posSlope(!Slope!)"
codeblock = """def posSlope(slope):
if slope < 0:
return slope * -1
else:
return slope"""
arcpy.CalculateField_management(ShapeFileLine, "Slope", expression, "PYTHON_9.3", codeblock)
``````

Or if you wanted to do it all at once (I assume startz/endz are both float):

``````expression = "calcSlope(!END_Z!, !START_Z!, !LENGTH_3D!)"
codeblock = """def calcSlope(endz, startz, length3d):
slope =  ((endz - startz)/length3d) * 100
if slope < 0:
return slope * -1
else:
return slope"""
arcpy.CalculateField_management(ShapeFileLine, "Slope", expression, "PYTHON_9.3", codeblock)
``````

• it works. but the quotations needs to be edited. – Anahita Kp Oct 22 '18 at 7:24

Just take the absolute value. For example, using an UpdateCursor in arcpy:

``````import arcpy

fc = r'C:/path/to/your.gdb/featureclass'

with arcpy.da.UpdateCursor(fc, "Slope") as cursor:
for row in cursor
row = abs(row)
cursor.updateRow(row)
``````