In this Python lesson, we will practice how to write a program to calculate the area of a triangle with inputs received from a user.
To calculate the area of a triangle, you have to know the base and height. This will help us to be able to calculate the area of the triangle. Below is the formula we will use to perform this operation in Python.
tirArea = (base * height) / 2
Example 1: Calculate the area of a given triangle with base and height
# Request base and height from user
triBase = float(input('Enter the base value: '));
triHeight = float(input('Enter the height value: '));
# Compute the area
triArea = (triBase * triHeight) / 2;
print('The area of the triangle is {} '.format(triArea))
Output
Enter the base value: 8
Enter the height value: 4
The area of the triangle is 16.0
In the above example, we were able to find the area of a triangle where two sides (base and height) were known. We can extend this practice to learn how to calculate the area of a triangle with three known sides. We can achieve this purpose using the Herons’ formula. Let’s assume a, b andc to be the three sides of the triangle we are discussing here. We will use the formula below for this practice which is the Heron’s formula.
s = (a+b+c)/2
triArea = √(s(s-a)*(s-b)*(s-c))
Example 2: Calculate the area of a given triangle with three sides
# Python Program to find the area of triangle
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# Calculate the semi-perimeter
s = (a + b + c) / 2
# Calculate the area
triArea = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %triArea)
Output
Enter first side: 6
Enter second side: 7
Enter third side: 8
The area of the triangle is 20.33