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
109 views
in Technique[技术] by (71.8m points)

Python Equality Check Difference

Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :

if a == 5 and b == 5:
    # do something

But a few days ago, I just involuntarily wrote a similar condition check as :

if a == b and b == 5:
    # do something 

which made me think, is there any difference between the two ? Also, there is one other way,

if a == b == 5:
    # do something

Is there any difference, any difference in terms of process of evaluation or execution or time taken ? and also which one is the better or which is better to use?

Is it related to the concept of transitivity ?

question from:https://stackoverflow.com/questions/23220141/python-equality-check-difference

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

1 Answer

0 votes
by (71.8m points)

Since they are basically equivalent, you could also consider the way you read/think about the code:

if a == 5 and b == 5:
  # do something

can be read as "if a equals 5 and b equals 5, then do ...". You have to think/conclude, that then also a will be equal to b.

This is opposite to the next example:

if a == b and b == 5:
  # do something 

This reads as "if a is equal to b and b equal to 5" and you have to conclude that then also a will be equal to 5

This is why I prefer the last example:

if a == b == 5:
  # do something

If you are familiar with Python (thanks to Itzkata) it is immediately clear that all three things must be equal (to 5). If however people with less experience in Python (but programming skills in other languages) see this, they might evaluate this to

if (a == b) == 5:

which would compare the boolean result of the first comparison with the integer 5, which is not what Python does and might lead to different results (consider for example with a=0, b=0: a==b==0 is true while (a==b) == 0 is not!

The manual says:

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

There might even be a difference, for example if evaulating b in your example would have a side effect.

Regarding transitivity, you are right.


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

...