[GIS] Using if else statement in Python Parser of Field Calculator in ArcGIS for Desktop

arcgis-desktopfield-calculatorpython-parser

I need help in writing the python script in the field calculator. I have three fields namely:
CODE
COMPLEX
Map1

Map1 is an empty field that I want to populate. I have a number of conditions to cater with in a single Map1 field. e.g. If CODE is 1.1.7 and COMPLEX is 4 then the output for Map1 should be 1.3, and these conditions continue with different CODE and COMPLEX values. I have been trying to write it like this but it doesn't work:

Parser
Python

Code Block

def Reclass( !CODE! , !COMPLEX! ):
    if ( !CODE! == 1.1.7 and !COMPLEX! == 4):
        return 1.3
    elif ( !CODE! == 3.2.0 and !COMPLEX! == 4):
        return 1.3    
    else:
        return 0

Map1 =

Reclass( !CODE! , !COMPLEX! )

Can anyone tell me where I am making a mistake? Or any other way of doing it?

Best Answer

The problem is in your code block.

Instead of:

def Reclass( !CODE! , !COMPLEX! ):
    if ( !CODE! == 1.1.7 and !COMPLEX! == 4):
        return 1.3
    elif ( !CODE! == 3.2.0 and !COMPLEX! == 4):
        return 1.3    
    else:
        return 0

try:

def Reclass( CODE , COMPLEX ):
    if ( CODE == "1.1.7" and COMPLEX == 4):
        return 1.3
    elif ( CODE == "3.2.0" and COMPLEX == 4):
        return 1.3    
    else:
        return 0

The exclamation marks are needed in your expression because there they are indicating field names but in the code block CODE and COMPLEX are Python variables and could be called a and b if you wanted.

The other problem is that your CODE field appears to be of type text so I have added quotes around the tests of its values. I cannot tell if your Map1 and COMPLEX fields are text or numbers so I have not put them there - you may need to!

Related Question