I recently started using ternary operator but I encountered a case where I needed to use multiple ternary operator in the same line, but they didn't seem to work as I expected.
Can someone please give a explanation why those line give different result.
x = 1 if True else 2 + 3 if False else 4 # x = 1, I expected 5
x = (1 if True else 2) + (3 if False else 4) # x = 5
If I add parentheses I get the expected result, but I don't understand what the parentheses change.
And if I rotated the addition, without the parentheses, I get the correct value.
3 if False else 4 + 1 if True else 2 # x = 5
However, I get wrong result if the second ternary operator is False:
3 if False else 4 + 1 if False else 2 # x = 5 # x = 2 ???
Is it because you shouldn't multiple ternary operator in the same line, or is their an other reason?
The reason is operator precedence. Conditional expressions have the lowest-but-one precedence, only lambda expression is lower. Therefore, the expression
1 if True else 2 + 3 if False else 4
is evaluated as
1 if True else ((2 + 3) if False else 4)
which returns 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With