How to calculate the area of a triangle in Python

In mathematics, it’s a common assignment to determine a triangle’s area. Given the measurements of a triangle’s three sides, we can apply Heron’s formula in Python to get the area of the triangle. Heron’s formula may be applied using basic arithmetic operations based on the idea of a triangle’s semi-perimeter.

Understanding Heron’s formula

The area of a triangle may be determined using Heron’s formula based on the measurements of its sides. The equation reads as follows:

area=(s×(sa)×(sb)×(sc))area = \sqrt{(s \times (s - a) \times (s - b) \times (s - c))}

where,

  • The area of the triangle is represented by areaarea.

  • ss stands for semi-perimeter, we can calculate by using the following formula:

s=(a+b+c)2s =\frac {(a + b + c)} {2}

  • The variables aa, bb and cc represents the three sides of a triangle.

Implementation

Let’s calculate the triangle’s area using Heron’s formula in Python.

import math
def calculate_triangle_area(a, b, c):
# Calculate the semi-perimeter
s = (a + b + c) / 2
# Calculate the area using Heron's formula
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
# Example usage
side_a = 5
side_b = 12
side_c = 13
triangle_area = calculate_triangle_area(side_a, side_b, side_c)
print("The area of the triangle is:", triangle_area)

Explanation

  • Line 4: We define a function called calculate_triangle_area that takes three arguments: a, b, and c, representing the lengths of the triangle’s sides.

  • Line 6: By summing the three side lengths and dividing the total by 2, we determine the semi-perimeter s within the function.

  • Line 9: We calculate the area by multiplying the semi-perimeter s with the differences between the semi-perimeter and each side length and taking the square root of the result using math.sqrt().

  • Line 11: It returns the calculated area from the function.

  • Line 19: We provide the side lengths of a triangle (5, 12, and 13) and assign the result of calling the calculate_triangle_area function to the variable triangle_area.

  • Line 20: We print the result, displaying the area of the triangle.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved