Write a program to Calculate the Area of a Triangle in Python
Python 3 Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Python Program to find the area of triangle # to take inputs from the user a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) |
Output:

The code you provided is a simple Python program that calculates the area of a triangle given the lengths of its three sides.
The program starts by using the input() function to prompt the user to enter the three sides of the triangle, a, b, and c. The user’s input is stored as a string, so it needs to be converted to a float using the float() function.
Next, the program calculates the semi-perimeter of the triangle by dividing the sum of the three sides by 2 and assigns the result to the variable s.
Then, the program uses the Heron’s formula which is a method for finding the area of a triangle when you know the lengths of all three sides. The formula is: area = (s*(s-a)(s-b)(s-c)) ** 0.5
Finally, the print() function is used to output the area of the triangle to the console. The % operator is used to format the output and insert the value of area into the string that is passed to the print() function. The %0.2f within the string is a format specifier, it tells Python to format the number as a floating-point number with 2 decimal places.
The output will depend on the input provided by the user, for example, if the user inputs 3, 4 and 5 as sides, the output will be “The area of the triangle is 6.00”
Take your time to comment on this article.
