Editor

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

triangle_type.py
a = 7 # or: a = float(input("Enter side 1: "))
b = 7 # or: b = float(input("Enter side 2: "))
c = 10 # or: c = float(input("Enter side 3: "))
print("Sides:", a, b, c)
if a <= 0 or b <= 0 or c <= 0:
print("Sides must be greater than zero")
elif a + b <= c or a + c <= b or b + c <= a:
# Each side must be shorter than the other two added together
print("These sides cannot form a triangle")
elif a == b == c:
print("It is an equilateral triangle")
elif a == b or b == c or a == c:
print("It is an isosceles triangle")
else:
print("It is a scalene triangle")
Output
Sides: 7 7 10
It is an isosceles triangle

How it works

  1. Sides of zero or less are rejected first.
  2. 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.
  3. a == b == c is a chained comparison that is true only when all three sides are equal.
  4. 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

Also checking for a right angle
def triangle_type(a, b, c):
x, y, z = sorted([a, b, c]) # z is the longest side
if x + y <= z:
return "not a triangle"
if x == z:
kind = "equilateral"
elif x == y or y == z:
kind = "isosceles"
else:
kind = "scalene"
if x * x + y * y == z * z:
kind += " and right-angled"
return kind
for sides in [(5, 5, 5), (3, 4, 5), (2, 2, 3), (1, 2, 8)]:
print(sides, "->", triangle_type(*sides))
Output
(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

Counting different sides with a set
a, b, c = 6, 8, 6
names = {1: "equilateral", 2: "isosceles", 3: "scalene"}
different = len({a, b, c}) # a set keeps only distinct values
print(f"Sides {a}, {b}, {c}: {names[different]} triangle")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises