# Field Calculation - Python - If/Then over multiple data columns

I have some VB code saved that looks at two columns of data, and populates a third with the low value.

Pre-logic Script Code:

``````Dim output as double
if [MIN_LEFT] < [MIN_RIGHT] Then
output = [MIN_LEFT]
else
output = [MIN_RIGHT]
end if

low = output
``````

I've never used Python before, but I see that I'm going to have to if I want to do this calculation! But I'm stumped by the comparison of the two columns, and how to define that. Can anyone help me? (And I apologize if this is overly basic!)

-

What you want to do in the codeblock for Python is define a function, and then call the function using your attributes as parameters as follows:

``````def comparison(left,right):
if left < right:
return left
else:
return right

output = comparison(!MIN_LEFT!,!MIN_RIGHT!)
``````

Then, all you need in the calculation is `output`, as you already had for VBScript.

-
Thank you so much! That worked perfectly & now I have a better understanding of it! –  Leslie Dec 6 '11 at 20:27
Glad to help, @Leslie! If you could accept it as the correct answer, it would be much appreciated :) –  nmpeterson Dec 6 '11 at 20:33

Your question is somewhat similar to one that was asked recently. As you can see, declaring functions is a rather different affair in python, and you are not required to denote types (such as double) ahead of time. You should look into the Calculate Field examples in the resource center to give you a good idea of what your syntax looks like.

Important points:

• Fields are denoted with double !s (like !MIN_LEFT!).
• In the expression, you can call the function and create a variable with the returned value (as @nmpeterson shows), or return it directly from the function by putting the function call in the expression box.
• Be careful with indentation, as it is how functions and control blocks (if/else) are identified.

I would definitely recommend you look up the nuts and bolts of python functions. They are quite simple to start and will do you a lot of good in the future if you get them down now.

-
Thank you very much. I appreciate the resources. I will be definitely spending some time learning Python! –  Leslie Dec 6 '11 at 20:27

For this simple example, you can use an inline-if statement (does not require codeblock):

``````!MIN_LEFT! if !MIN_LEFT! < !MIN_RIGHT! else !MIN_RIGHT!
``````

For more complicated logic (e.g., if-elif-...), use a `def` and codeblock.

-