Home:ALL Converter>Why a != b != c is not equal to a != b and a != c and b != c?

Why a != b != c is not equal to a != b and a != c and b != c?

Ask Time:2019-10-15T21:30:25         Author:Jironymo

Json Formatter

I want to check if 3 values a, b , c are not equal to each other. Given that a == b == c equals to a == b and b == c and a == c, why does python give a different answer for a != b != c ?

Thanks!

This is a task from an introductory course to Python:

"How many of the three integers a, b, c are equal?"

This is a simple task and I got the correct answer with the following:

a = int(input()); b = int(input()); c = int(input());

if a != b and a != c and b != c:
    print(0)
elif a == b == c:
    print(3)
else:
    print(2)

Yet, I can not understand why a != b != c wouldn't do the job in the initial if statement.

From a != b != c I expect the same as from a != b and a != c and b != c

Author:Jironymo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58395948/why-a-b-c-is-not-equal-to-a-b-and-a-c-and-b-c
Dani Mesejo :

When you use a != b != c you are actually using chained comparison, from the documentation:\n\n\n Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are\n comparison operators, then a op1 b op2 c ... y opN z is equivalent to\n a op1 b and b op2 c and ... y opN z, except that each expression is\n evaluated at most once.\n\n\nSo a != b != c is actually a != b and b != c, which is different from a != b and a != c and b != c, for example:\n\na, b, c = 1, 2, 1\nprint(a != b != c)\nprint(a != b and a != c and b != c)\n\n\nOutput\n\nTrue\nFalse\n",
2019-10-15T13:38:52
khalid_salad :

The \"equals\" operator is transitive:\n\n\n if a == b and b == c, then a == c\n\n\nThe \"not equals\" operator is not:\n\n\n if a != b and b != c, a could still equal c\n\n\nWhy? Take \n\n\n a = 3, b = 4, c = 3\n\n\nThen\n\n\n a != b, b != c, but a == c\n",
2019-10-15T13:33:32
yy