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.
The area of a triangle may be determined using Heron’s formula based on the measurements of its sides. The equation reads as follows:
where,
The area of the triangle is represented by .
stands for semi-perimeter, we can calculate by using the following formula:
Let’s calculate the triangle’s area using Heron’s formula in Python.
import mathdef calculate_triangle_area(a, b, c):# Calculate the semi-perimeters = (a + b + c) / 2# Calculate the area using Heron's formulaarea = math.sqrt(s * (s - a) * (s - b) * (s - c))return area# Example usageside_a = 5side_b = 12side_c = 13triangle_area = calculate_triangle_area(side_a, side_b, side_c)print("The area of the triangle is:", triangle_area)
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