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, andcstore the three sides of the triangle (set to6each in this example). - Find the Semi-Perimeter (
s): Adding all three sides and dividing by2gives half of the triangle's perimeter. - Compute Square Root with
** 0.5: Raising the products * (s - a) * (s - b) * (s - c)to the power of0.5calculates the square root without needing to import themathmodule. - 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
Post a Comment