-1

I just started a new job and in one of the procedures I was given for one of my tasks I found this piece of code. It just adds a comment to a field that's already filled up. For instance, field1 might have an ABC001 code, and in the final stage we need it to show as 'Feature not found: ABC001'

'Comment ' + (!field1! if !field1! else '')

'Comment' + !field1! works as well. I don't understand what the condition in the first piece of code does.

  • Apparently, the condition is just telling explicitly to not show anything in case the field value is empty. – umbe1987 Sep 12 at 16:14
  • 1
    'Comment ' + !field1! may cause error if value of field1 is None. If it is None then the empty string '' is used – BERA Sep 12 at 16:23
2

What the !field1! if !field1! else '' expression does is evaluate if the corresponding value of !field1! exists or not. If there is a value, then it keeps that value and adds it to 'Comment'. However, if there is no value (it evaluates to None) it will keep and empty string ('').

Here is an illustrative example:

Suppose the value of field1 is 'ABC001' for the first row. Run the folowings lines in a Python console:

value = 'ABC001'
print(value if value else '')
# It will print ABC001

This way, the resulting value for the new field will be Comment ABC001 in the first row. On the other hand, consider that the value of field1 is empty (None) in the second row. Now try to run these lines:

value = None  # this is not a string but rather a Python object
print(value if value else '')
# It will print nothing as '' it is an empty string

Therefore, the value of field1 in the second row will be just Comment.

You could change the condition and play around with different values. For example:

value = None  # this is not a string but rather a Python object
print(value if value else 'new comment')
# It will print new comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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