Select to view content in your preferred language

Python in field calculator

4438
5
Jump to solution
04-17-2015 02:38 PM
JessicaKnapp
Deactivated User

I have two fields: landuse classification numbers (1-5) and soil rating numbers (1-4). The values of the third field, CN values, depend on what numbers the other other two fields are. For example, if the landuse number is 1 and the soil rating number is 3, the CN value should be 70. I'm attempting to do this via python if-then statement in the field calculator but keep running in problems with it. The most common error message is that it has invalid parameters. Here is what I am trying. I'm completely new to python and would appreciate any help!!

0 Kudos
1 Solution

Accepted Solutions
JessicaKnapp
Deactivated User

I figured it out and now it works like a charm! I started to continue with additional if statements but the difference was to use == instead of = and to use quotations around the return field.

View solution in original post

5 Replies
JessicaKnapp
Deactivated User

I figured it out and now it works like a charm! I started to continue with additional if statements but the difference was to use == instead of = and to use quotations around the return field.

DanPatterson_Retired
MVP Emeritus

some syntactical errors

  • missing a final ) in the def statement
  • equality check is == , not = ... the later is an assignment statement
  • I use & instead of 'and' ... prefer & but six of one... ( lu == 1) and (soil == 3)
  • enclose conditions in ( ) juuuust to be sure
  • always provide a return of some sort, otherwise it is a crap shoot

Ok format

>>> def cn(lu,soil):
...  if (lu == 1) & (soil== 3):
...  return 70
... 
>>> lu = 1
>>> soil = 3
>>> cn(lu,soil)
70
>>>

better format  (I don't share perfect

>>> def cn(lu,soil):
...  if (lu == 1) & (soil== 3):
...  val = 70
...  else:
...  val = -999
...  return val
...
>>> cn(1,4)
-999
>>> cn(1,3)
70
>>>
DarrenWiens2
MVP Honored Contributor

^ missing final ) after "I don't share perfect"

DanPatterson_Retired
MVP Emeritus

It is those damn smiley faces...they corrupt the end of the line ()

BlakeTerhune
MVP Regular Contributor
  • always provide a return of some sort, otherwise it is a crap shoot

I like this suggestion from Dan Patterson​. In addition Joshua Bixby​ recommends using one return for a single exit point (like Dan's "better format" code above), rather than having multiple returns. The Python Code Style agrees.

When a function grows in complexity it is not uncommon to use multiple return statements inside the function’s body. However, in order to keep a clear intent and a sustainable readability level, it is preferable to avoid returning meaningful values from many output points in the body.

0 Kudos