What kind of logic does Python uses to handle Boolean expressions?

Viewed 48

So I just started learning Python, and while I was just playing with the shell I came around a weird thing.

print(5!=6==True,"=",True) #Gave False=True
print(5!=6==False,"=",True) #Gave False=True
print(5!=6!=True,"=",True) #Gave True=True

Can anyone explain to me why does this happen

2 Answers

What's interesting about this is it isn't about regular operator precedence. Adding parentheses doesn't give the same result:

>>> 5!=6==True
False
>>> (5!=6)==True
True
>>> 5!=(6==True)
True

The first one is actually parsed as a chained comparison:

5!=6 and 6==True

which is True and False (result False).

The more natural use of chained comparisons is:

x = 5
if 0 < x < 10:  # True

which is parsed as:

0 < x and x < 10
Related