Usage of the “==” operator for three objects

痞子三分冷 提交于 2019-12-01 02:58:10

问题


Is there any computational difference between these two methods of checking equality between three objects?

I have two variables: x and y. Say I do this:

>>> x = 5
>>> y = 5
>>> x == y == 5
True

Is that different from:

>>> x = 5
>>> y = 5
>>> x == y and x == 5
True

What about if they are False?

>>> x = 5
>>> y = 5
>>> x == y == 4
False

And:

>>> x = 5
>>> y = 5
>>> x == y and x == 4
False

Is there any difference in how they are calculated?

In addition, how does x == y == z work?

Thanks in advance!


回答1:


Python has chained comparisons, so these two forms are equivalent:

x == y == z
x == y and y == z

except that in the first, y is only evaluated once.

This means you can also write:

0 < x < 10
10 >= z >= 2

etc. You can also write confusing things like:

a < b == c is d   # Don't  do this

Beginners sometimes get tripped up on this:

a < 100 is True   # Definitely don't do this!

which will always be false since it is the same as:

a < 100 and 100 is True   # Now we see the violence inherent in the system!


来源:https://stackoverflow.com/questions/13792604/usage-of-the-operator-for-three-objects

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