Vaibhav Mishra
Vaibhav Mishra

Reputation: 12102

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 )

it evaluates correctly to 1 , what is happening in the first case.

Upvotes: 1

Views: 309

Answers (3)

Sphinx
Sphinx

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

Ashwini Chaudhary
Ashwini Chaudhary

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

Vladimir
Vladimir

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

Related Questions