Reputation: 5
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
Upvotes: 0
Views: 5546
Reputation: 101
If you want this to work in one expression you can just do:
print(a != b != c != a)
This should allow you to stay away from any scary-looking "and" statements.
Upvotes: 0
Reputation: 11
The "equals" operator is transitive:
if a == b and b == c, then a == c
The "not equals" operator is not:
if a != b and b != c, a could still equal c
Why? Take
a = 3, b = 4, c = 3
Then
a != b, b != c, but a == c
Upvotes: 1
Reputation: 61910
When you use a != b != c
you are actually using chained comparison, from the documentation:
Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
So a != b != c
is actually a != b and b != c
, which is different from a != b and a != c and b != c
, for example:
a, b, c = 1, 2, 1
print(a != b != c)
print(a != b and a != c and b != c)
Output
True
False
Upvotes: 2