Python Program to Check Whether a Triangle Is Equilateral, Isosceles or Scalene
Beginner · Basics
A triangle is equilateral when all three sides are equal, isosceles when exactly two sides are equal, and scalene when all three sides are different. Not every three lengths make a triangle, though, because each side must be shorter than the other two put together, so this program checks that first.
Program
Sides: 7 7 10 It is an isosceles triangle
How it works
- Sides of zero or less are rejected first.
- The triangle rule says any two sides must add up to more than the third; 2, 3 and 6 fail it, because 2 + 3 is less than 6.
a == b == cis a chained comparison that is true only when all three sides are equal.- If any one pair of sides matches, the triangle is isosceles, and if none do, it is scalene.
Other ways to write it
Also checking for a right angle
(5, 5, 5) -> equilateral (3, 4, 5) -> scalene and right-angled (2, 2, 3) -> isosceles (1, 2, 8) -> not a triangle
Sorting puts the longest side last, so the single test x + y <= z replaces three checks and also rejects zero or negative sides. Pythagoras then spots a right-angled triangle.
Counting different sides with a set
Sides 6, 8, 6: isosceles triangle
A set throws away repeats, so it holds 1, 2 or 3 different side lengths, which matches the three types exactly. It assumes the sides already form a valid triangle.
Try it yourself
Set the sides to 2, 3 and 6 and check that the program says they cannot form a triangle.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises