Skip to content Skip to sidebar Skip to footer

Python Ternary Operator Behaviour

when I evaluate the following operation 0 if True else 1 + 1 if False else 1 it evaluates to 0 however when I write with brackets like ( 0 if True else 1 ) + ( 0 if False else 1 )

Solution 1:

0 if True else 1 + 1 if False else 1

is actually:

(0) if (True) else ((1 + 1) if (False) else (1))

which is definitely differs from what you want:

((0) if (True) else (1)) + ((1) if (False) else (1))

Solution 2:

as ternary operator is read from left to right and + has lower precedence than conditional operators. So, these two are equivalent:

>>> 0 if True else 1 + 1 if False else 1
0
>>> 0 if True else ( (1 + 1) if False else 1)
0

Solution 3:

ternary operator looks like "condition ? value if true : value if false",but it seems that python doesn't support it ,but we can use if-else to replace.The stype is something like "condition if (b_1) else b_2,so you can depend it to match.if b_1 is True,the value is condition,if b_2 is True,the value is b_2.


Post a Comment for "Python Ternary Operator Behaviour"