1

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.

3 Answers 3

10
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))
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

-1

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.

3 Comments

a if b else c is python implementation of ternary operator.
Python's value if condition else alternative is ternary operator as you can use it as subexpression.
I know it,but I think your interpretation is better,and I just want to make the reasons behind the results clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.