# Using if else syntax in field calculator with Python?

I want to calculate a field in the field calculator that are dependent on the values in 4 other columns.

My columns are "A", "B", "C" and "D"

Now I want to fill the column "X" with:

if "A" and "B" are equal "0" I want to do "calculation_1_(A,B,C,D)"

if only "A" equals "0" I want to do "calculation_2_(A,B,C,D)"

if only "B" equals "0" I want to do "calculation 3_(A,B,C,D)"

else I want to do "calculation_4_(A,B,C,D)"

Can somebody give me the code for this? I am struggling with syntax and if/else structure...

This python function implements the logic you described in your question:

``````def calculate_X(A,B,C,D):
if A == 0 and B == 0:
X = calculation_1(A,B,C,D)

elif A == 0 and B != 0 and C != 0 and D != 0:
X = calculation_2(A,B,C,D)

elif B == 0 and A != 0 and C != 0 and D != 0:
X = calculation_3(A,B,C,D)

else:
X = calculation_4(A,B,C,D)

return X
``````

Then access the function using the expression

``````calculate_X(!A!, !B!, !C!, !D!)
``````

It is a little unclear based on the question whether the values of "C" and "D" should be tested for calculations 2 and 3 (since they are not tested for calculation 1). If "C" and "D" should not be tested, then just use `A == 0 and B != 0` instead of `A == 0 and B != 0 and C != 0 and D != 0`

Example of code in field calculator / calculate field:

Field Name: X

Expression: `calc1(!A!,!B!,!C!,!D!)`

Expression type: PYTHON_9.3

Code Block(/Pre-Logic Script Code):

``````def calc1(a,b,c,d):
if a==0 and b==0:
return a+b+c+d+1+2+3+4
elif a==0 and b<>0:
return a-b-c-d
else:
return a+b-c+d
``````

Be sure to check "Code Block":

``````def calc_X(A,B,C,D):
if A == 0 and B == 0:
return calculation_1(A,B,C,D)

elif A == 0 and B != 0:
return calculation_2(A,B,C,D)

elif B == 0 and A != 0:
return calculation_3(A,B,C,D)

else:
return calculation_4(A,B,C,D)
``````

Then: `X = calc_X(!A!, !B!, !C!, !D!)`