Open In App

Calculate the Area of a Triangle - Python

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A triangle is a closed-shaped two-dimensional polygon having three sides and three corners. The corners are called vertices and the sides are called edges. In this article, we will see how we can calculate the area of a triangle in Python.

Using Heron's Formula

When the lengths of all three sides of the triangle are known, you can use Heron's Formula. The formula is:

A = \sqrt{s(s - a)(s - b)(s - c)}

where:

  • a,b,c are the lengths of the sides of the triangle.
  • s is the semi-perimeter, calculated as:
    s = \frac{a + b + c}{2}
Python
a = 7
b = 8
c = 9
s = (a + b + c) / 2

res = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print(res)

Output
26.832815729997478

Using Base and Height

For a right-angled triangle or when the base and height are given, you can calculate the area using the formula:

\text{Area} = \frac{1}{2} \times \text{base} \times \text{height}

Python
b = 8
h = 9

res = 0.5 * b * h
print(res)

Output
36.0

Using coordinates of vertices

If the coordinates of the three vertices of the triangle are known, you can calculate the area using the Shoelace Theorem (also known as the Surveyor's Formula):

Formula
surveyor's formula

Where (x1y1),(x2,y2) and (x3,y3) are the coordinates of the three vertices.

Python
x1, y1 = 0, 0
x2, y2 = 5, 0
x3, y3 = 5, 7

res = 0.5 * abs(x1*y2 + x2*y3 + x3*y1 - y1*x2 - y2*x3 - y3*x1)
print(res)

Output
17.5

Next Article
Practice Tags :

Similar Reads