Home » Programming » Python Program to Calculate the Area of a Triangle

# Python Program to Calculate the Area of a Triangle

In this post, we will be investigating the Python Program to Calculate the Area of a Triangle. We will find the area of a triangle and clarify the linguistic structure; simply referred to as syntax of the program.

## Algorithm to Calculate the Area of a Triangle

Here, the basic formula to calculate the area of a triangle is `area = √(s(s-a)*(s-b)*(s-c))`; where a, b and c are the three sides of a triangle; and s is the semi-perimeter calculated as `s = (a+b+c)/2`.

We will follow the following steps to calculate the area of a triangle.

``````Step 1: Start
Step 2: Take the three sides of a triangle i.e. a,b and c
Step 3: Calculate the semi-perimeter as
s = (a+b+c)/2
Step 4: Finally, calculate the area of a triangle as
area = √(s(s-a)*(s-b)*(s-c))
Step 5: End``````

New to Python Programming? Get started with Python Programming!

## Calculate the Area of a Triangle in Python

Focusing on the Python program to calculate the area of a triangle, let’s jump into the source code.

### Example 1: Program with static input

```# Three sides of a triangle
a = 2
b = 3
c = 4

# 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 a triangle is %0.2f" %area)```

Note : For calculating the area we took the exponentiation of the other part of the formula with 0.5 as 1/2 = 0.5. Get more to know!

The output of above code snippet is,

``The area of a triangle is 2.90``

### Example 2: Program with user input

```# Three sides of a triangle
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 a triangle is %0.2f" %area)```

The output for the above code snippet is,

``````Enter first side: 2
Enter second side: 3
Enter third side: 4
The area of a triangle is 2.90``````

## Explanation

When we have three sides of a triangle we can calculate the area of a triangle using Heron’s formula. Unlike other triangle area formulae, there’s no got to calculate angles or other distances within the triangle first.

We performed calculation of area of triangle for different possible cases; static input and user input shown in the example above.

You can also check —>