How to use Python Pre-Logic in Field Calculator

3923
4
01-07-2013 08:17 AM
by Anonymous User
Not applicable
I am trying to use if/then python pre-logic in field calculator to only change the value of a field when one or two other fields equal a predefined value.  I can get it to work partially using the following code but it does not keep the original values for fields where "if=FALSE".  I have tried using "pass" but it does not seem to work the way I need it to.

Pre-logic:
def myfunc(SYMBOL,ID,OPER_MAINT_LEVEL):
    if ID == "4648" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)":
        return 4
    if ID == "4654":
        return 4
    if ID == "4663C" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)":
        return 4
    else:
        SYMBOL
SYMBOL=
myfunc( !SYMBOL!, !ID!, !OPER_MAINT_LEVEL! )
Tags (2)
0 Kudos
4 Replies
MathewCoyle
Frequent Contributor
I think you want to do this.
def myfunc(SYMBOL, ID, OPER_MAINT_LEVEL):
    if ((ID == "4648" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)") or
            (ID == "4663C" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)")
            (ID == "4654")):
        return 4
    else:
        return SYMBOL
0 Kudos
by Anonymous User
Not applicable
I think you want to do this.
def myfunc(SYMBOL, ID, OPER_MAINT_LEVEL):
    if ((ID == "4648" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)") or
            (ID == "4663C" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)")
            (ID == "4654")):
        return 4
    else:
        return SYMBOL


Thanks.  I did not think to put it all into one query line. This seems to work except when ID and/or OPER_MAINT_LEVEL is null it does not return the value for SYMBOL.  Is there a way still return the SYMBOL value when there are nulls in these fields?  What about adding
elif ID== "NULL" or Oper =="NULL": return SYMBOL/
0 Kudos
MathewCoyle
Frequent Contributor
Nulls are a little tricky. You could give something like this a try.

if not ID or not OPER_MAINT_LEVEL:
    return SYMBOL
0 Kudos
by Anonymous User
Not applicable
Nulls are a little tricky. You could give something like this a try.

if not ID or not OPER_MAINT_LEVEL:
    return SYMBOL


Here is how I got it to work using str(!OPER_MAINT_LEVEL!):

def myfunc(SYMBOL,ID,OPER_MAINT_LEVEL):
    if not ID or not OPER_MAINT_LEVEL:
        return SYMBOL
    if ((ID == "4648" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)") or 
        (ID == "4654") or
        (ID == "4663C" and OPER_MAINT_LEVEL == "1 - BASIC CUSTODIAL CARE (CLOSED)")):
        return 4
    else:
        return SYMBOL

Expression:
SYMBOL =
myfunc(!SYMBOL!, !ID!, str(!OPER_MAINT_LEVEL!) )


Thanks for your help on this.
0 Kudos