Calculate Area of a Triangle in Python
0.5 * base * height. Height means perpendicular height, not a slanty side.
BeginnerBasic Python ProgramsExample 11 of 25
calculate-area-of-a-triangle.py
1# Program to calculate the area of a triangle23base = float(input("Enter the base of the triangle: "))4height = float(input("Enter the height of the triangle: "))56area = 0.5 * base * height78print("The area of the triangle is:", area)
Output
Enter the base of the triangle: 10 Enter the height of the triangle: 5 The area of the triangle is: 25.0
In this one
- 0.5 * base * height
- 1//2 is 0 — don't integer-divide the half
What's going on
Area = ½ × base × height. 0.5 * base * height.
Height is the perpendicular one. Plug in a side length by accident and the number is still a number, just the wrong area. The program cannot save you from that.
1/2 * base * height also works in Python 3. 1//2 is 0. Don't.
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.