Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

if statement - Different evaluation results of python if else expression

The following two expressions use if...else...

I can understand the c2 result. But I wonder why c1 returns a different result.

a = 10
c1 = 10 + a if a > 20 else -a
c2 = 10 + (a if a > 20 else -a)

print(c1, c2)

Output:

-10    0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...