This is an operator precedence issue, +
has higher precedence than if
, so
c1 = 10 + a if a > 20 else -a
is evaluated as
c1 = (10 + a) if a > 20 else -a
= 20 if 10 > 20 else -10
= -10 # because 10 <= 20
where your second statement is evaluated as written
c2 = 10 + (a if a > 20 else -a)
= 10 + (10 if 10 > 20 else -10)
= 10 + -10 # because 10 <= 20
= 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…