# Conditional statement in field calculator using Python parser ArcGIS

I have looked at many threads on here asking about coding nested if-then or conditional statements in field calculator in ArcGIS. This seems to be a common problem for beginner programmers. I've attempted to learn some Python and I really wanted to figure this out myself, but am apparently failing.

The Problem: I have 3 columns (a,b,c) that have numeric values. I want a statement to assign them a value based on their numeric values > 0. For example, If a>0, then 1 and if b>0, then 2, and if c>0 then 3. There may or may not be a situation where 2 columns > 0 and I'm not sure how to deal with that.

I've tried variations of the code below. My errors are incorrect syntax on line 1. Am I using an incorrect function? I can't find any sites listing Python functions that include half of what I see people using here. Am I referencing the wrong columns or the columns incorrectly? I my spacing wrong?

Pre-Logic Script

``````def Calc( Cockle, Butter, Gaper)
if Cockle >0:
return 1
elif Butter >0:
return 2
elif Gaper >0
return 3
else 0
``````

ClamType (new field) =

``````Calc(!Cockle!, !Butter!, !Gaper!)
``````

I tried function Reclass. What am I missing?

You're just missing some colons and a `return`:

``````def Calc(Cockle, Butter, Gaper):
if Cockle > 0:
return 1
elif Butter > 0:
return 2
elif Gaper > 0:
return 3
else:
return 0
``````

If you want to handle situations where multiple variables are greater than zero, you need more nesting:

``````def Calc(Cockle, Butter, Gaper):
if Cockle > 0:
if Butter > 0:
if Gaper > 0:
return #value for all > 0
else:
return #value for cockle, butter > 0
else:
if Gaper > 0:
return #value for cockle, gaper > 0
else:
return #value for cockle > 0
else:
if Butter > 0:
if Gaper > 0:
return #value for butter, gaper > 0
else:
return #value for butter > 0
else:
if Gaper > 0:
return #value for gaper > 0
else:
return #value for none > 0
``````
• Thank you for this! The nesting was really tripping me up and this code helped me learn more about indenting with statements. Commented Jan 30, 2018 at 20:08

Is it possible that 2 of your input values (Butter and Gaper, say) would both be greater than zero for the same record? The way your code is written, if you have a Butter value of 1 and a Gaper value of 27, your function will return 2. That may or may not be what you want.

You have a few typos in your code:

1. You're missing a colon at the end of line 1.
2. Also missing a colon at the end of line 6.
3. In line 8, you need a colon after 'else' and you need a return statement (on the next line, not the same line) to return that 0 value.

This should work:

``````def Calc(Cockle, Butter, Gaper):
if Cockle >0:
return 1
elif Butter >0:
return 2
elif Gaper >0:
return 3
else:
return 0
``````
• Thank you for catching those errors. Seem obvious in hindsight. Now I know the last else needs ":" Commented Jan 30, 2018 at 20:07