Python Program to Calculate Area of Triangle
area = 0.5 * base * height. For example, area = 0.5 * 10 * 5 calculates the area when base is 10 and height is 5.Examples
How to Think About It
Algorithm
Code
base = float(input('Enter the base of the triangle: ')) height = float(input('Enter the height of the triangle: ')) area = 0.5 * base * height print('Area of the triangle is', area)
Dry Run
Let's trace the example where base = 10 and height = 5 through the code
Input base
User enters base = 10
Input height
User enters height = 5
Calculate area
area = 0.5 * 10 * 5 = 25.0
Print result
Output: Area of the triangle is 25.0
| Step | Variable | Value |
|---|---|---|
| 1 | base | 10 |
| 2 | height | 5 |
| 3 | area | 25.0 |
Why This Works
Step 1: Get inputs
We ask the user to enter the base and height, converting them to numbers with float() so we can do math.
Step 2: Calculate area
We use the formula 0.5 * base * height because the area of a triangle is half the product of its base and height.
Step 3: Show output
We print the result so the user can see the area calculated.
Alternative Approaches
a = float(input('Enter side a: ')) b = float(input('Enter side b: ')) c = float(input('Enter side c: ')) s = (a + b + c) / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 print('Area of the triangle is', area)
base = int(input('Enter base: ')) height = int(input('Enter height: ')) area = 0.5 * base * height print(f'Area of the triangle is {area}')
Complexity: O(1) time, O(1) space
Time Complexity
The calculation involves a fixed number of arithmetic operations, so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and the result, so space usage is constant.
Which Approach is Fastest?
Both base-height formula and Heron's formula run in constant time, but base-height is simpler and faster since it uses fewer operations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Base and Height Formula | O(1) | O(1) | When base and height are known |
| Heron's Formula | O(1) | O(1) | When all three sides are known |