Reputation: 12102
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 )
it evaluates correctly to 1 , what is happening in the first case.
Upvotes: 1
Views: 309
Reputation: 425
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.
Upvotes: -1
Reputation: 250891
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
Upvotes: 3
Reputation: 10493
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))
Upvotes: 10