Python Program to Find the Area of a Triangle

1. Introduction

Calculating the area of a triangle is a common task in geometry. In Python, this can be done easily by applying Heron's formula, which allows us to compute the area if we know the lengths of all three sides of the triangle.

Heron's formula states that the area of a triangle with sides of length a, b, and c is sqrt(s*(s-a)*(s-b)*(s-c)), where s is the semi-perimeter of the triangle, calculated as (a+b+c)/2.

2. Program Steps

1. Define the lengths of the three sides of the triangle.

2. Calculate the semi-perimeter of the triangle.

3. Apply Heron's formula to calculate the area.

4. Print the area of the triangle.

3. Code Program

import math

# Function to calculate the area of a triangle using Heron's formula
def triangle_area(a, b, c):
    # Calculate the semi-perimeter
    s = (a + b + c) / 2
    # Calculate the area
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))
    return area

# Lengths of the sides of the triangle
side_a = 5
side_b = 6
side_c = 7
# Calculate the area
area = triangle_area(side_a, side_b, side_c)
# Print the area
print(f"The area of the triangle is: {area}")

Output:

The area of the triangle is: 14.696938456699069

Explanation:

1. The math module is imported to use the sqrt function for calculating the square root.

2. The function triangle_area is defined to calculate the area of a triangle given the sides a, b, and c.

3. s is computed as the semi-perimeter of the triangle.

4. area is calculated using Heron's formula inside the math.sqrt function.

5. The lengths of the sides of the triangle side_a, side_b, and side_c are defined.

6. The triangle_area function is called with these side lengths to calculate the area.

7. The calculated area is printed, which in this case is approximately 14.697 for the sides of lengths 5, 6, and 7.

8. The f-string is used to format the output, clearly indicating the result.

Comments