In this Python code example, we will discuss a Python program to calculate the area of a triangle. The resulting area will be displayed as output using the print() function in Python.
Formula for Calculating the Area of Triangle
Let us consider a triangle with three sides represented by variables x,y, and z. To find the area of the triangle, we first need to calculate its semi-parameter, which is represented by s.
Following is the formula for calculating the semi-perimeter of a triangle:
s = (x+y+z)/2
Now, by using the semi-parameter, we can calculate the area of a triangle by using the following formula:
Area of Triangle = √(s(s-a)*(s-b)*(s-c))
Python Program to Calculate the Area of a Triangle
By using the formulas mentioned in the previous section, we can write a simple Python program that calculates the area of a triangle. Also, we can prompt the user to provide the measures of all the sides of a triangle.
#Get values of the three sides of the triangle as input from the user x = int (input("Enter the length of 1st side of Triangle:")) y = int (input("Enter the length of 2nd side of Triangle:")) z = int (input("Enter the length of 3rd side of Triangle:")) # Calculate the semi-parameter of the traingle s = (x+y+z)/2 #Calculate the area of the Triangle area = (s*(s-x)*(s-y)*(s-z)) ** 0.5 #Output the area value print (f"The Area of Triangle is: {area}")
Output:
Enter the length of 1st side of Triangle:10
Enter the length of 2nd side of Triangle:10
Enter the length of 3rd side of Triangle:10
The Area of Triangle is: 43.30127018922193
Takeaway
The Python program discussed above calculates the area of a triangle whose sides are provided as input by the user.
Hi! I am Pankaj, a full-time content specialist and a part-time programmer and marketer. I love to explore new places and also new ideas. I am an inquisitive person with a passion to learn new skills through every possible opportunity that comes in the way.