Python Program to Calculate the Area of a Triangle

Introduction

Calculating the area of a triangle is a fundamental geometry problem. This tutorial will guide you through creating a Python program that calculates the area of a triangle when the lengths of its base and height are provided.

Problem Statement

Create a Python program that:

  • Takes the base and height of a triangle as input.
  • Calculates the area using the formula:
    [
    \text{Area} = \frac{1}{2} \times \text{base} \times \text{height}
    ]
  • Displays the calculated area.

Example:

  • Input: base = 10, height = 5
  • Output: The area of the triangle is 25.0

Solution Steps

  1. Take Input for Base and Height: Use the input() function to get the base and height of the triangle from the user.
  2. Convert Input to Numeric Values: Convert the input strings to floats using float().
  3. Calculate the Area: Use the formula to calculate the area of the triangle.
  4. Display the Result: Use the print() function to display the area of the triangle.

Python Program

# Python Program to Calculate the Area of a Triangle
# Author: https://www.javaguides.net/

# Step 1: Take input for base and height of the triangle
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

# Step 2: Calculate the area using the formula
area = 0.5 * base * height

# Step 3: Display the result
print(f"The area of the triangle is {area}")

Explanation

Step 1: Take Input for Base and Height

  • The input() function prompts the user to enter the base and height of the triangle. The inputs are converted to floats using float() to handle decimal values.

Step 2: Calculate the Area

  • The area of the triangle is calculated using the formula:
    [
    \text{Area} = \frac{1}{2} \times \text{base} \times \text{height}
    ]
    The result is stored in the variable area.

Step 3: Display the Result

  • The print() function is used to display the area of the triangle. The f-string format is used to include the area value directly within the string.

Output Example

Example:

Enter the base of the triangle: 10
Enter the height of the triangle: 5
The area of the triangle is 25.0

Example:

Enter the base of the triangle: 7.5
Enter the height of the triangle: 3.2
The area of the triangle is 12.0

Conclusion

This Python program demonstrates how to calculate the area of a triangle using the base and height. It’s a simple yet effective example that helps beginners understand basic arithmetic operations and user input handling in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top