0

I try to calculate some fields with the field calculator using a simple if-else condition. I would like to write the values in the field volume, based on some calculations including values of fields wert and shape_area (no coordinates).

The code works, when I use just one integer/no math functions. If I try it like it should be, I get syntax error .

The example:

import math
    def muh(bedingung, wert, Shape_Area):
       if (bedingung == "hallo"):
        value = (4.3 * math.log(!wert!)) * !Shape_Area!
       elif (bedingung == "echo"):
        value = (2.7 * math.log(!wert!) * !Shape_Area!

       return value

And expression volume = "muh(!bedingung!, !wert!, !Shape_Area!)

I can't seem to find the fault. The problem lies between numeric values and "string" (?), I guess, I have to escape or convert some parts of the code?

2
  • Wrong use of parameters. Instead *!Shapearea! Use Shapearea inside def block.
    – FelixIP
    Commented Apr 18, 2020 at 9:44
  • Bang delimiters are only used once, at the expression level. Inside the Python block you can only use Python.
    – Vince
    Commented Apr 18, 2020 at 12:32

1 Answer 1

1

I would try this:

import math

def muh(bedingung, wert, Shape_Area):
   if (bedingung == "hallo"):
       value = (4.3 * math.log(wert)) * Shape_Area
   elif (bedingung == "echo"):
       value = (2.7 * math.log(wert) * Shape_Area

   return value

And

volume = muh(!bedingung!, !wert!, !Shape_Area!)

You only need the field delimiters of exclamation marks in your Expression so that it knows what fields to get values from.

Then in the function you define you are assigning new variables that you could name anything but have chosen (sensibly) to make similar/identical to your field names.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.