ArcGIS Field Calculator nested elif is None not working

I am calculating a field based on two other fields in ArcMap 10.2 using python.

My Pre-Logic Script Code is

def myfunc(legend,Btype):

if(legend == 'Apple'): return 'Banana' elif(legend == 'Cranberry'): return 'Date' elif(legend == 'Elderberry'): if(Btype.startswith('Fig')): return 'Grape' elif(Btype.startswith('Lychee')): return 'Mango' elif Btype is None: return 'Olive' else: return 'Pear' else: return 'Raspberry'

Mostly this function works, however in the case that legend is "Elderberry" and Btype is "Null" the function returns "Null" rather than "Olive"

The problem only occurs when I nest the "is None" in the if statement.

Move your "is None" check up to the first evaluation.

if Btype is None: return 'Olive' elif (Btype.startswith('Fig')): return 'Grape' elif(Btype.startswith('Lychee')): return 'Mango'

Basically, if Btype is null, you can't do .startswith, etc. on it.

Watch the video: ArcGIS Pro: Using Python in Field Calculators Code Block to Average Across Field Values (October 2021).