Why does Python (0<0==0) return False?

Asked 2 years ago, Updated 2 years ago, 17 views

When I was looking at Queue.py on Python 2.6, I saw this code.

def full(self):
    """Return True if the queue is full, False otherwise
    (not reliable!)."""
    self.mutex.acquire()
    n = 0 < self.maxsize == self._qsize()
    self.mutex.release()
    return n

If maxsize is 0, the queue will never be filled, so it should be false, but

In my opinion, when maxsize is 0, that code is 0 < 0 == 0, so I think I will return True, but I returned False normally.

Why is that?

>>> 0 < 0 == 0
False
>>> (0) < (0 == 0)
True
>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True

python chained-comparsion

2022-09-22 22:13

1 Answers

Python performs a special operation when there are multiple relational operators. It's hard to explain in words, for example,

In C/Java, when checking whether x falls within [0,100],

0 <=x  && x <= 100

Python, but sharing

.
0 <= x <= 100

That's enough. This comparison is called chained comparisons. For more information, see Comparations.

So

False because it is the same as 0 <0 == 0 -> (0 < 0) and (0 == 0).


2022-09-22 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.