Calculate field in python if else statement

4560
2
01-21-2014 12:13 PM
AndrewL
Occasional Contributor II
Hi I have the following code. Basically I am trying to say when the field "daily_minFlag" equals 's', then I want to calculate the "daily_min" field to be null.

    fieldName = "daily_min"
    expression = "getClass(!daily_minFlag!)"
    codeblock = """def getClass(minFlag):
        if minFlag == 's':
            return ""
        else:
            return !daily_min!"""
    arcpy.CalculateField_management(out_feature_class, fieldName, expression, "PYTHON_9.3", codeblock)


I am getting an error when using the else statement. If I replace "return !daily_min!" with "return 1", it works fine, but I don't want it to equal 1, I want it to not change the daily_min value. So I think there is something wrong with my !daily_min! syntax. Thank you.
0 Kudos
2 Replies
RichardFairhurst
MVP Honored Contributor
Hi I have the following code. Basically I am trying to say when the field "daily_minFlag" equals 's', then I want to calculate the "daily_min" field to be null.

    fieldName = "daily_min"
    expression = "getClass(!daily_minFlag!)"
    codeblock = """def getClass(minFlag):
        if minFlag == 's':
            return ""
        else:
            return !daily_min!"""
    arcpy.CalculateField_management(out_feature_class, fieldName, expression, "PYTHON_9.3", codeblock)


I am getting an error when using the else statement. If I replace "return !daily_min!" with "return 1", it works fine, but I don't want it to equal 1, I want it to not change the daily_min value. So I think there is something wrong with my !daily_min! syntax. Thank you.


You have to feed in both the flag and the daily_min fields through your expression into the code block.  So it should be:

    fieldName = "daily_min"
    expression = "getClass(!daily_minFlag!, !daily_min!)"
    codeblock = """def getClass(minFlag, daily_min):
        if minFlag == 's':
            return ""
        else:
            return daily_min"""
    arcpy.CalculateField_management(out_feature_class, fieldName, expression, "PYTHON_9.3", codeblock)
0 Kudos
AndrewL
Occasional Contributor II
Thanks! I was getting an error but I changed the return "" to return None and that works.

    fieldName = "daily_min"
    expression = "getClass(!daily_minFlag!, !daily_min!)"
    codeblock = """def getClass(minFlag, daily_min):
        if minFlag == 's':
            return None
        else:
            return daily_min"""
    arcpy.CalculateField_management(out_feature_class, fieldName, expression, "PYTHON_9.3", codeblock)


Thank you!
0 Kudos