I recently started using a ternary operator, but I came across a situation where I needed to use several ternary operators on the same line, but they did not seem to work as I expected.
Can someone please give an explanation of why this line gives a different result.
x = 1 if True else 2 + 3 if False else 4
x = (1 if True else 2) + (3 if False else 4)
If I add brackets, I get the expected result, but I do not understand that the brackets are changing.
And if I turned the addition, without parentheses, I get the correct value.
3 if False else 4 + 1 if True else 2
However, I get the wrong result if the second ternary operator is False:
3 if False else 4 + 1 if False else 2
Is it because you shouldn't use multiple ternary operators on the same line or is this their other reason?
source
share