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

前端 未结 9 1543
误落风尘
误落风尘 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:04

    I believe Python has special case handling for sequences of relational operators to make range comparisons easy to express. It's much nicer to be able to say 0 < x <= 5 than to say (0 < x) and (x <= 5).

    These are called chained comparisons. And that's a link to the documentation for them.

    With the other cases you talk about, the parenthesis force one relational operator to be applied before the other, and so they are no longer chained comparisons. And since True and False have values as integers you get the answers you do out of the parenthesized versions.

提交回复
热议问题