Calculating the Area of a Triangle Based on Side Lengths
The following example demonstrates how to calculate the area of a triangle using the lengths of its three sides provided by the user:
Example (Python 3.0+):
# -*- coding: UTF-8 -*- # Input the lengths of the triangle's three sides a = float(input('Enter the length of the first side: ')) b = float(input('Enter the length of the second side: ')) c = float(input('Enter the length of the third side: ')) # Calculate the semi-perimeter s = (a + b + c) / 2 # Calculate the area using Heron's formula area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 print('The area of the triangle is %0.2f' % area)
When you run this code, the output will be:
Output:
$ python test.py Enter the length of the first side: 5 Enter the length of the second side: 6 Enter the length of the third side: 7 The area of the triangle is 14.70
In this example, the program calculates the area of a triangle using Heron’s formula. The user inputs the lengths of the three sides, and the semi-perimeter is computed as . The area is then calculated by taking the square root of .