Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Calculate Area of a Triangle in Python

Calculate a triangle’s area from base and perpendicular height in Python. This beginner formula exercise keeps units straight and explains why 1//2 is wrong.

BeginnerBasic Python ProgramsExample 11 of 25
calculate-area-of-a-triangle.py
1# Program to calculate the area of a triangle
2
3base = float(input("Enter the base of the triangle: "))
4height = float(input("Enter the height of the triangle: "))
5
6area = 0.5 * base * height
7
8print("The area of the triangle is:", area)

Sample Output

The area of the triangle is: 25.0

0.5 × 10.0 × 5.0 is 25.0 square units.

In this one

  • Translate a geometry formula
  • Use perpendicular height
  • Track squared units in an area result

How it works

  1. 1

    Read base and height with float.

  2. 2

    Multiply their product by 0.5.

  3. 3

    Print the stored area without changing the measurements.

Edge cases

Zero height

Enter height 0.

The formula gives zero area, representing a collapsed triangle.

Mixed units

Enter a base in meters and height in centimeters.

Convert to matching units first or the numeric result has no useful area meaning.

What's going on

Area is one half times base times height. In Python that is 0.5 * base * height. A triangle fills half the area of a matching rectangle, which is where the half comes from.

Height means the perpendicular distance to the base, not whichever sloping side is easiest to measure. The computer will happily multiply the wrong measurements. Correct syntax is not a substitute for correct geometry.

The sample uses base 10 and height 5, so half of 50 is 25.0 square units. Both inputs must use the same length unit. 1/2 also equals 0.5 in Python 3; 1//2 equals zero and would wipe out the whole product. The code does not reject zero or negative dimensions, so physical validation is a separate step.

After this program

If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which height belongs in this formula?

Pick an answer to check it.

Question 2

What happens if 0.5 is replaced by 1//2?

Pick an answer to check it.

Questions people ask

Which height belongs in this formula?

The perpendicular height to the chosen base, not an arbitrary side length.

What happens if 0.5 is replaced by 1//2?

1//2 is zero, so multiplying by it makes the area zero.

What unit does the result use?

It uses square units, such as square centimeters when both lengths are centimeters.