# Python if then codeblock in field calculator

4204
5
09-14-2015 07:45 AM
Occasional Contributor

I need to write an if then code block for field calculator to see if the value in field A equals 0, and if it is to make the value in field B equal -1.  Else do nothing.  How can I do this?  FIeld A is type float & field B is type interger.

Tags (2)
1 Solution

Accepted Solutions
New Contributor III

Assuming you are using ArcMap since you mentioned field calculator:
Right click the field you wish to change to -1 and calculate that field.

Switch the radio button to Python

In the code block enter:

def changefield(whatif,okthen):

if (whatif == 0):

okthen = -1

return okthen

Then in the text box below FIELDB  =

Enter: changefield(!FIELDA!, !FIELDB!)

5 Replies
MVP Esteemed Contributor

They can be emulated using this syntax

simple comparison and reclass

" True condition " if !some_field! == "some_value" else " False condition "

ie .  "Agricultural 10 Acres" if !Zone! == "A-10" else "False"

1  if !A! == 0 else -999

assuming you are calculating in the B field, using python and you can't do nothing...so I put in -999 and you can replace it with integer nothingness

New Contributor III

Assuming you are using ArcMap since you mentioned field calculator:
Right click the field you wish to change to -1 and calculate that field.

Switch the radio button to Python

In the code block enter:

def changefield(whatif,okthen):

if (whatif == 0):

okthen = -1

return okthen

Then in the text box below FIELDB  =

Enter: changefield(!FIELDA!, !FIELDB!)

MVP Esteemed Contributor

Python has conditional expressions, a.k.a., ternary operators, that can be used in situations like this one.  Using a ternary operator eliminates the need for using a code block and defining a function.

`-1 if !FieldA! == 0 else !FieldB!`
MVP Esteemed Contributor

hmmm my previous thoughts exactly

New Contributor III

Excellent. Nice to know!