Python Program to find the Area of Triangle
Summary:
This is a basic maths question which is easy to solve using a pen and paper. It is very easy to write a Python program to find the area of a triangle in an optimized way.
Python Program: Area of a triangle using the Math module
Math module is one of the most important parts of Python for mathematical operations.
Copy
import math
a = 5.0
b = 6.0
c = 7.0
#Uncomment below line to take user Input
#a,b,c = map(float, input("Enter three sides separated by space\n").split(" "))
s = (a+b+c)/2
areaOfTrangle = math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of triangle is {0:.2f}".format(areaOfTrangle))
Output
Area of triangle is 14.70
The logic of the program is simple. We used Heron’s formula to calculate the area of a triangle whose three sides are given.
Heron’s formula:
Find the perimeter using the formula s = (a+b+c)/2
.
Find the area of a triangle using the formula √(s_(s-a)_(s-b)*(s-c))
.
At line 10 of Python code, we calculate the area of a triangle using the formula as described above.
The last line is to print the resulted area of a triangle with two-digit precision {0:.2f}
.
Python Code: Area of triangle without Math module
There are several ways to calculate square root in Python. We can calculate the area of a triangle in Python without using any module.
Copy
areaOfTrangle = (s*(s-a)*(s-b)*(s-c))**0.5
This is another way to calculate the area of a triangle in Python after calculating the perimeter.
Join Our Youtube Channel
Subscribe