简体   繁体   中英

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM