# Python in field calculator

3701
5
04-17-2015 02:38 PM
New Contributor II

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

Tags (3)
1 Solution

Accepted Solutions
New Contributor II

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.

5 Replies
New Contributor II

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.

MVP Esteemed Contributor

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>>>`
MVP Honored Contributor

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

MVP Esteemed Contributor

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

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.