Javaexercise.com

Python Program To Calculate Area Of Triangle In Python

To get the area of a triangle, here, we will write a python program that contains custom code and math formulas to get an accurate result. Let's understand with examples.

When Side lengths of the Triangle are given

The area of a triangle whose length of the sides are given can be calculated using the formula:

Area = sqrt(s*(s-s1)*(s-s2)*(s-s2))
where s1, s2 and s3 are lengths of sides of
triangle and s = (s1+s2+s3)/2

A triangle is not a valid triangle if any one side length is 0 or the sum of any two sides is less than the third side. In this case, the area of the triangle cannot be calculated.

Algorithm to find are of Triangle

  1. Get used input and store into s1, s2, s3 variables

  2. Check for valid triangle

  3. if sides are valid then calculate the area

  4. else print "not a valid triangle"

  5. Display triangle area

Python Program to calculate the area of a triangle with Sides

If you are calculating the area of the triangle and sides are given then you can use the below code. It first checks the sides and then return the area.

import math
​
# Input s1, s2, and s3
s1 = float(input("Enter side 1 length"))
s2 = float(input("Enter side 2 length"))
s3 = float(input("Enter side 3 length"))
​
# check for valid triangle
if (s1 < 0 or s2 < 0 or s3 < 0 or 
               (s1 + s2 <= s3) or 
               (s1 + s3 <= s2) or 
                (s2 + s3 <= s1)): 
    print("not a valid triangle")
# if valid then calculate area
else:
    s = (s1 + s2 + s3) / 2; 
    area = math.sqrt(s * (s - s1) * (s - s2) * (s - s3)); 
    print("The area is " +str(area))

Output:

Enter side 1 length 21

Enter side 2 length 34

Enter side 3 length 53

The area is 188.78559267062727

Calculate the area of triangle When co-ordinates are given

When coordinates of the triangle are given, then we can calculate the area of the triangle using the shoelace formula:

area = | 1/2 [ (x1y2 + x2y3 + x3y1) - (x2y1 + x3y2 + x1y3) ] |

We will take two lists X and Y, both storing the x and y coordinates of the triangle.

Algorithm

  1. Take a list X having x coordinates 

  2. Take a list Y having y coordinates 

  3. Declare a variable area and assign an initial value 0.0

  4. Declare a variable j and assign an initial value 2

  5. Start a for loop from 0 to 2

  6. Calculate area and assign to area variable

  7. Reassign j with i

  8. Calculate absolute area

  9. Display area 

Python Program to calculate the area of triangle When co-ordinates are given

X = [0, 2, 4]
Y = [1, 3, 7]
​
area = 0.0
    
j = 2
for i in range( 0, 3) :
    area = area + (X[j] + X[i]) * (Y[j] - Y[i])
    j = i  
​
area =  abs(area // 2.0)
​
print("Area is " +str(area))

Output:

Area is 2.0