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.
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.
Get used input and store into s1, s2, s3 variables
Check for valid triangle
if sides are valid then calculate the area
else print "not a valid triangle"
Display triangle area
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
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.
Take a list X having x coordinates
Take a list Y having y coordinates
Declare a variable area and assign an initial value 0.0
Declare a variable j and assign an initial value 2
Start a for loop from 0 to 2
Calculate area and assign to area variable
Reassign j with i
Calculate absolute area
Display area
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