Calculate Area Of Triangle

The provided Python code calculates the area of a triangle based on its base and height. It defines a function called calculate_triangle_area that takes two parameters, namely the base length and height of the triangle. Inside the function, it employs the formula for the area of a triangle, which is 0.5 times the base multiplied by the height. The result is then returned by the function. The code also includes an example usage section where the user is prompted to input the base length and height of the triangle. Subsequently, the calculated area is displayed to the user. This code serves as a simple and reusable tool for computing the area of a triangle, allowing users to input their own triangle dimensions for computation.


Source code

def calculate_triangle_area(base, height):
    area = 0.5 * base * height
    return area

# Example usage:
base_length = float(input("Enter the base length of the triangle: "))
height = float(input("Enter the height of the triangle: "))

triangle_area = calculate_triangle_area(base_length, height)
print(f"The area of the triangle is: {triangle_area}")

Description

  1. Function Definition:
    • The code begins by defining a function called calculate_triangle_area.The function takes two parameters, base and height, representing the base length and height of the triangle.
    def calculate_triangle_area(base, height):
  2. Area Calculation:
    • Inside the function, the area of the triangle is calculated using the formula: 0.5 * base * height.The result of this calculation is stored in the variable area.
    area = 0.5 * base * height
  3. Return Statement:
    • The function then returns the calculated area using the return statement.
    return area
  4. Example Usage:
    • The code proceeds to demonstrate the usage of the calculate_triangle_area function.It prompts the user to input the base length and height of the triangle using the input function, converting the input to a float.base_length = float(input(“Enter the base length of the triangle: “)) height = float(input(“Enter the height of the triangle: “))
  5. Function Invocation:
    • The function is then called with the user-provided base and height values.The returned area is stored in the variable triangle_area.triangle_area = calculate_triangle_area(base_length, height)
  6. Display Result:
    • Finally, the code prints the calculated area of the triangle using an f-string.
    print(f"The area of the triangle is: {triangle_area}")
  7. Example Output:
    • When the user runs the code, they are prompted to enter the base length and height of the triangle. The code then calculates and displays the corresponding area.

Screenshot


Download

By Admin

Leave a Reply

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