Calculate the Area of a Triangle in Python Using Heron's Formula

When you only know the lengths of a triangle's three sides—and not its height—Heron's formula lets you calculate the exact area in just a few lines of Python. Watch my quick 60-second walkthrough below, or copy the complete script to test it yourself.

Python Code: Heron's Formula

No external libraries are required for this script—everything runs using standard Python math operators.

# This program calculates a triangle's area using Heron's formula

# Define the three side lengths (equilateral triangle example)
a = 6
b = 6
c = 6

# Calculate the semi-perimeter
s = (a + b + c) / 2

# Calculate the final area
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5

# Print the result rounded to 2 decimal places
print(f"The area of the triangle is {area:.2f}")

Sample Output

The area of the triangle is 15.59

How This Script Works

  • Define Side Lengths: Variables a, b, and c store the three sides of the triangle (set to 6 each in this example).
  • Find the Semi-Perimeter (s): Adding all three sides and dividing by 2 gives half of the triangle's perimeter.
  • Compute Square Root with ** 0.5: Raising the product s * (s - a) * (s - b) * (s - c) to the power of 0.5 calculates the square root without needing to import the math module.
  • Format the Output: Using {area:.2f} inside an f-string rounds the final answer cleanly to two decimal places.

Want to make it interactive? Try replacing a = 6 with float(input("Enter side a: ")) so users can type any triangle dimensions at runtime. Subscribe on YouTube (@programmer_script99) for more quick Python tutorials!

Comments

Popular posts from this blog

๐ŸŒ๐Ÿค– Modi Calls for Inclusive AI, Unveils MANAV Framework

Amazon CodeGuru

☁️ Cloud Services: The Hidden Playground of Cybercriminals