3

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • There may be more exact duplicates, but the quote from the documentation in the accepted answer for this duplicate does explain what is happening. –  Apr 05 '18 at 04:19
  • Your last operation that is carried out is 'True != True', which is false. -5 is being compared to False. False it being compared to True. But the second to last True is being compared to True. True != True is False. – Simeon Ikudabo Apr 05 '18 at 04:21
  • 2
    Read operation chaining here - https://docs.python.org/3/reference/expressions.html#comparisons – Aritesh Apr 05 '18 at 04:23
  • Using parenthesis helps you control the order of evaluation and brings more clarity to the developer's intent. ((-5 != False) != True) != True – Minato Apr 05 '18 at 04:27

1 Answers1

2

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.