► Python program to calculate area of a triangle


Steps followed:
1. take length and breadth of a rectangle as input from user
2. validate user input by converting to float
3. calculate area of rectangle using formula √p(p−a)(p−b)(p−c) where p = (a+b+c)/2
4. print area of rectangle


Program

#python program to calculate area of a triangle

#import math library
import math

#take all three sides of triangle as input from user
side1=input("Enter first side of triangle: ")
side2=input("Enter second side of triangle: ")
side3=input("Enter third side of triangle: ")

try:
    side1=float(side1)
    side2=float(side2)
    side3=float(side3)

    p = (side1 + side2 + side3)/2
    c = p * (p - side1) * (p - side2) * (p - side3)

    #calculate area of triangle
    area = math.sqrt(c)

    #print area of triangle
    print("---output---")
    print("area of triangle with sides %0.2f,%0.2f,%0.2f is %0.2f"%(side1,side2,side3,area))

except:
    print("---error---")
    print("please enter a valid length")


Output

Enter first side of triangle: 30
Enter second side of triangle: 40
Enter third side of triangle: 50
---output---
area of triangle with sides 30.00,40.00,50.00 is 600.00

 

Enter first side of triangle: s1
Enter second side of triangle: s2
Enter third side of triangle: s3
---error---
please enter a valid length





Also Read: