Python Program to Calculate Area of any Triangle using its coordinates

Hey Coder! In this article, we are going to learn how to calculate the area of any triangle using its coordinates with the help of a Python program.

Formula to Calculate Area of a Triangle

Before we go to the Python coding part, let’s look for the formula.

Let A(x1, y1), B(x2, y2) and C(x3, y3) be the coordinates of a triangle. We can calculate the area of triangle ABC using the Mathematical formula

Area = |(1/2)*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))|

Calculating the Area without modulus may give a negative value. As we know that Area cannot be negative we only take the magnitude by applying modulus to the formula.

We use abs() method in the program to get the absolute value or the magnitude.

Syntax:

abs(x)

x can be an integer or a floating-point number also.

NOTE:
If the value of Area is Zero, We can say that a Triangle cannot be formed using the input coordinates.

Program

Let us first take the input of the coordinates from the user in order to calculate the area of the triangle using the above formula.

We must convert the input to an integer using int() method as default input is considered as a string.

Now, Let us Calculate the Area of the triangle using the above formula and store it in the variable called Area. As we need to consider only magnitude for Area we use abs() method to get magnitude or absolute value.

We can now print the value of Area.

Let us tell the user that we cannot form a triangle using the input coordinates through a print statement if the value of Area is Zero.

x1 = int(input("Enter the value of x1 :"))
y1 = int(input("Enter the value of y1 :"))
x2 = int(input("Enter the value of x2 :"))
y2 = int(input("Enter the value of y2 :"))
x3 = int(input("Enter the value of x3 :"))
y3 = int(input("Enter the value of y3 :"))
Area = abs((0.5)*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))
print("Area of the Triangle is ",Area)
if Area == 0:
    print("A Triangle cannot be formed using the input coordinates!")

Input & Output :

1.

Enter the value of x1 :0
Enter the value of y1 :0
Enter the value of x2 :1
Enter the value of y2 :2
Enter the value of x3 :7
Enter the value of y3 :10
Area of the Triangle is 2.0

2.

Enter the value of x1 :0
Enter the value of y1 :0
Enter the value of x2 :1
Enter the value of y2 :1
Enter the value of x3 :10
Enter the value of y3 :10
Area of the Triangle is 0.0
A Triangle cannot be formed using the input coordinates!

Hurray! We have learned how to calculate the Area of the Triangle using Python.

Thanks for reading this article. I hope it helped you someway. Also, do check out our other related articles below:

 

Leave a Reply

Your email address will not be published. Required fields are marked *