I was surprised at how Python's ternary operator works

It's a matter of course even if you don't think about it, and I think you all know it, but it was interesting, so I'll post it.

I used the ternary operator as follows when judging correctness in Python.

hoge.py


print 'No.' + str(i) + ' is ' + 'True' if test[i][1] == res else 'False' + ' (true label:' + test[i][1] + ', predicted label: ' + res + ')'

result,

No.1 is True
False (true label: 3, predicted label: 0)
No.3 is True
No.4 is True
No.5 is True
No.6 is True
No.7 is True
No.8 is True
No.9 is True
No.10 is True
No.11 is True
False (true label: 1, predicted label: 2)
No.13 is True
No.14 is True
False (true label: 1, predicted label: 2)

Since the result of each correctness is before and after the operator, it works for the whole sentence before and the whole sentence after. If you enclose it in parentheses, it will work as expected, but I thought that you could do various things with this usage. That's it.

Recommended Posts

I was surprised at how Python's ternary operator works
I was surprised at how to save objects with python, which is lean and very energy-saving.
I want to know how LINUX works!
I added a function to CPython (ternary operator)