python ternary operator behaviour

天涯浪子 提交于 2019-11-27 08:28:41

问题


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.


回答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))



回答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



回答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.



来源:https://stackoverflow.com/questions/11922302/python-ternary-operator-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!