Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of the chaining of comparison operators [duplicate]

I am confused on how does the != operator works in python. I am new to python programming.

I know simple != simply checks whether the LHS expression and RHS expression are not equal.

for eg:

True != False

returns True.

My question is how it works in series of != operators.

e.g.: when I type

-5 != False != True != True

in my python interactive session it returns False, but if I solve it step by step I get the answer True.

Solving it step by step:

-5 != False returns True

True != True returns False

False != True returns True

So it should return True but it returns False. I don't know why.

like image 736
Deepesh Sidhwani Avatar asked Sep 17 '25 04:09

Deepesh Sidhwani


1 Answers

In Python, this comparation is equivalent to:

-5 != False and False != True and True != True

I.e.,

result = (-5 != False) and (False != True) and (True != True)
result =    (True)     and     (True)      and     (False)
result = False

See more in:https://docs.python.org/3/reference/expressions.html#comparisons.

like image 117
Gean Santos Avatar answered Sep 19 '25 18:09

Gean Santos