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:
where,
-
The area of the triangle is represented by .
-
stands for semi-perimeter, we can calculate by using the following formula:
- The variables , and represents the three sides of a triangle.
Implementation
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)
Explanation
-
Line 4: We define a function called
calculate_triangle_areathat takes three arguments:a,b, andc, 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-perimeterswithin the function. -
Line 9: We calculate the
areaby multiplying the semi-perimeterswith the differences between the semi-perimeter and each side length and taking the square root of the result usingmath.sqrt(). -
Line 11: It returns the calculated
areafrom the function. -
Line 19: We provide the side lengths of a triangle (
5,12, and13) and assign the result of calling thecalculate_triangle_areafunction to the variabletriangle_area. -
Line 20: We print the result, displaying the area of the triangle.
Free Resources