Editor

Python Program to Find the Area of a Triangle

Beginner · Basics

The area of a triangle is half its base times its height, where the height is measured at right angles to the base. When you only know the three sides, Heron's formula gives the area instead, and this page shows both ways.

Program

area_of_triangle.py
base = 10 # in cm; or: base = float(input("Enter the base: "))
height = 6 # in cm; or: height = float(input("Enter the height: "))
area = 0.5 * base * height
print("Base:", base, "cm")
print("Height:", height, "cm")
print("Area of the triangle:", area, "square cm")
Output
Base: 10 cm
Height: 6 cm
Area of the triangle: 30.0 square cm

How it works

  1. The formula is area = 1/2 x base x height, written in Python as 0.5 * base * height.
  2. The height must be the straight-up distance from the base to the opposite corner, not the length of a sloping side.
  3. Multiplying by 0.5 always gives a decimal, so the area prints as 30.0.

Other ways to write it

Using Heron's formula (three sides)

Using Heron's formula (three sides)
import math
a, b, c = 5, 6, 7 # the three sides in cm
if a + b > c and a + c > b and b + c > a:
s = (a + b + c) / 2 # half the perimeter
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print(f"Sides {a}, {b}, {c}: semi-perimeter s = {s}")
print(f"Area = {area:.2f} square cm")
else:
print("These sides cannot form a triangle")
Output
Sides 5, 6, 7: semi-perimeter s = 9.0
Area = 14.70 square cm

Heron's formula needs only the three sides: area = square root of s(s - a)(s - b)(s - c), where s is half the perimeter. The check first makes sure each pair of sides is longer than the third, or there is no triangle.

From the corners on a graph

From the corners on a graph
x1, y1 = 0, 0
x2, y2 = 4, 0
x3, y3 = 0, 3
area = abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2
print("Area of the triangle with these corners:", area, "square units")
Output
Area of the triangle with these corners: 6.0 square units

When the corners are points on a graph, this coordinate formula gives the area directly, and abs() keeps it positive whichever order the corners are listed in.

Try it yourself

Use Heron's formula on the sides 3, 4 and 5 and check that it matches 1/2 x 3 x 4.

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