The following program works exactly as expected:
data = input("Input the length of three sides of a triangle: ").strip()
if data.count(',') != 2:
print("You did not enter the lengths of three sides: ")
a, b, c = data.split(', ')
def triangle_type(s1, s2, s3):
if s1 == s2 == s3:
return print("The values entered represent an equilateral triangle.")
elif s1 != s2 and s1 != s3 and s2 != s3:
return print("The values entered represent a scalene triangle.")
else:
if s1 == s2 or s1 == s3 or s2 == s3:
return print("The values entered represent an isosceles triangle.")
triangle_type(int(a), int(b), int(c))
However, if I change the second condition to the following:
elif s1 != s2 != s3:
it does NOT work as expected.
If I input 3, 6, 3 I get:
Input the length of three sides of a triangle: 3, 6, 3
The values entered represent a scalene triangle.
This is incorrect. This should clearly match condition #3 (isosceles).
It works correctly with the first version of the code.
I am confused on two things:
1) Why does the second version work improperly?
2) If the second version is invalid, then why does the first condition work correctly?
Given the above behavior with the != operator, I would expect to have to treat a == b == c like a == b and a == c and b == c, but I don't have to.
When you chain comparisons in Python, it and
s them together, and it only does as many comparisons as you have comparison operators. So
if s1 == s2 == s3:
is equivalent to
if s1 == s2 and s2 == s3:
That works because if both of those conditions are True
, then s1
must also be equal to s3
(because they're both equal to s2
).
However
if s1 != s2 != s3:
is equivalent to
if s1 != s2 and s2 != s3:
As you've discovered, for the values 3, 6, and 3, the above two conditions are True
, but the third assumed condition (s1 != s3
) is not True
. This doesn't work as you expect because Python isn't making that third comparison.