7

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!)

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Dec 5, 2011 at 21:58

3 Answers 3

10

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.

answered Dec 5, 2011 at 22:17
0
7

Your question is somewhat similar to Using Range in Python expression of ArcGIS Field Calculator?

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 exclamation marks (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.

answered Dec 5, 2011 at 22:20
0
6

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.

answered Mar 1, 2012 at 22:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.