Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator behavior

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?

like image 781
Yassine Faris Avatar asked Dec 05 '22 12:12

Yassine Faris


1 Answers

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.

like image 187
ducminh Avatar answered Dec 30 '22 10:12

ducminh