python ternary operator behaviour

后端 未结 3 1716
南方客
南方客 2020-12-12 04:50

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

相关标签:
3条回答
  • 2020-12-12 05:41
    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))
    
    0 讨论(0)
  • 2020-12-12 05:44

    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.

    0 讨论(0)
  • 2020-12-12 05:56

    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
    
    0 讨论(0)
提交回复
热议问题