How to Calculate Triangle Area in Python

Here this example focuses on how to calculate the triangle area with Python.

Method

Assuming the sides of the triangle are a, b, and c respectively, the area of the triangle can be obtained by the Helen formula:

S = sqrt[p(p-a)(p-b)(p-c)]

The p in the formula is a half cycle: p = (a+b+c)/2

Source Code

``````
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Enter three sides
a = float(input('Enter the first side of the triangle: '))
b = float(input('Enter the second side of the triangle: '))
c = float(input('Enter the third side of the triangle: '))

# Calculated area based on Helen formula
temp = (a + b + c) / 2
area = (temp * (temp - a) * (temp - b) * (temp - c)) ** 0.5

# Print out area
print('The area of the triangle is %0.2f' % area)
``````

Output:

1) Equilateral triangle

``````Enter the first side of the triangle: 5
Enter the second side of the triangle: 5
Enter the third side of the triangle: 5
The area of the triangle is 10.83
``````

2) Right triangle

``````Enter the first side of the triangle: 3
Enter the second side of the triangle: 4
Enter the third side of the triangle: 5
The area of the triangle is 6.00
``````

3) Isosceles triangle

``````Enter the first side of the triangle: 3
Enter the second side of the triangle: 3
Enter the third side of the triangle: 5
The area of the triangle is 4.15
``````

Think More

You can also add a judgment to determine whether the three sides can form a triangle.

Subscribe
Notify of