Why does the expression 0 < 0 == 0 return False in Python?

前端 未结 9 1563
误落风尘
误落风尘 2020-11-22 01:48

Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange:

def full(self):
    \"\"\"Return True if the queue is full, False oth         


        
9条回答
  •  攒了一身酷
    2020-11-22 02:09

    Because

    (0 < 0) and (0 == 0)
    

    is False. You can chain together comparison operators and they are automatically expanded out into the pairwise comparisons.


    EDIT -- clarification about True and False in Python

    In Python True and False are just instances of bool, which is a subclass of int. In other words, True really is just 1.

    The point of this is that you can use the result of a boolean comparison exactly like an integer. This leads to confusing things like

    >>> (1==1)+(1==1)
    2
    >>> (2<1)<1
    True
    

    But these will only happen if you parenthesise the comparisons so that they are evaluated first. Otherwise Python will expand out the comparison operators.

提交回复
热议问题