I am trying to create a python label expression without having any python skills
I have 2 fields [FIELD1] and [FIELD2]
If [FIELD1] > 0 and [FIELD2] < 0
return "text:" [FIELD1] 'text:" [FIELD2]
return "text:" [FIELD1]
return 'text:" [FIELD2]
Any help would be greatly appreciated.
Solved! Go to Solution.
You could also define label classes based on those if statements, and then label each class accordingly.
Please refer to this help page as a start for building label expressions, and this post for posting code blocks.
Header 1 | Header 2 |
---|---|
If [FIELD1] > 0 and [FIELD2] < 0 return "text:" [FIELD1] 'text:" [FIELD2] | if (!FIELD1! > 0) and (!FIELD2! < 0): out = str(!FIELD1!) + str(!FIELD2!)
|
If [FIELD1] > 0 and [FIELD2] !< 0return "text:" [FIELD1] | elif (!FIELD1! > 0) and (!FIELD2! != 0):out = str(!FIELD1!) |
If [FIELD1] !> 0 and [FIELD2] < 0return 'text:" [FIELD2] | elif (!FIELD1! > 0) and (!FIELD2! != 0):out = str(!FIELD1!) |
else out = "no match' | |
return out |
Lets break this down into parts
Toggle on the Python parser, in the field calculator. The results must be put into a text field.
So as python code it becomes with 4 spaces for indents.
def check_cond(a,b):
"""two fields as input, """
if a > 0) and b < 0):
out = str(!FIELD1!) + str(!FIELD2!)
out = str(!FIELD1!)
out = str(a)
else
out = "no match'
Expression box
check_cond(!FIELD1!,!FIELD2!)
Always check the unexpected, never return prematurely, hence return out should be the last line
Just a note that this is a field calculator expression, not label expression, which is quite different. Of course, you could calculate the label to a new field, but that's an added step.
There are a few tricky little things, so here goes. I don't believe there is such thing as !<, use >= instead. You can't concatenate numbers to strings, cast to string using str(). You'll have to decide if you really mean "if, if, if" or "if, elif, elif" - either can be used if you know what it means.
def FindLabel ( [Field1] , [Field2] ): if [Field1] > 0 and [Field2] < 0: return "text: " + str( [Field1] )+ " text: " + str( [Field2] ) if [Field1] > 0 and [Field2] >= 0: text = "text: " + str([Field1] ) return text if [Field1] <= 0 and [Field2] < 0: return "text: " + str( [Field2] )
I went with the various label classes. Thanks for all the info though.
I'm glad you found a solution that worked for you, Scott. Do you mind marking this questions as answered? This accomplishes a couple of things: people will realize that you don't still need help, and also, other people in the future with the same question can find the answer easier. Thanks!
I'm a moderator and marked your suggestion correct.
Thanks Curtis!