Python Program to Calculate the Area of a Triangle

This Python program example shows how to calculate the area of a triangle based on user input for the base and height.

As a real-world use case scenario, imagine a construction worker needs to determine the area of a triangular section of a roof in order to calculate the amount of roofing material needed. They can input the base and height measurements into the program to quickly and accurately calculate the area of the triangle.

Example 1: Calculate the Area of a triangle with base and height.

base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

area = 0.5 * base * height

print(f"The area of the triangle is {area}.")

The program prompts the user to input the base and height of the triangle as floating-point numbers.

It then calculates the area using the formula “area = 0.5 * base * height” and outputs the result to the user with an f-string.

This program can be easily adapted for use in a variety of fields, including engineering, architecture, and construction.

Example 2: Area of a triangle with three sides.

This program will calculate the area of a triangle based on user input for the length of its three sides a, b, c.

If ab, and c are three sides of a triangle. Then, s = (a+b+c)/2 area = √(s(s-a)*(s-b)*(s-c))

import math

a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))

# Calculate the semiperimeter
s = (a + b + c) / 2

# Calculate the area using Heron's formula
area = math.sqrt(s * (s - a) * (s - b) * (s - c))

print(f"The area of the triangle is {area}.")

The program prompts the user to input the lengths of the three sides of the triangle as floating-point numbers. It then calculates the semiperimeter of the triangle (half of its perimeter) using the formula “(a + b + c) / 2”. Using the semiperimeter and the lengths of the sides, it then calculates the area of the triangle using Heron’s formula, which is “area = sqrt(s(s-a)(s-b)(s-c))”, where “s” is the semiperimeter.

Leave a Comment