CBSE Class 11 Computer Science Question 58 of 98

Python Programming Fundamentals — Question 20

Back to all questions
20
Question

Question 15

Modify the above function to take a third parameter called shape type. Shape type should be either triangle or rectangle. Based on the shape, it should calculate the area. Formula used:

Area of a Rectangle = length * width.

Solution
def calculate_area(base, height, shape_type):
    if shape_type == "triangle":
        area = (1/2) * base * height
    elif shape_type == "rectangle":
        area = base * height
    else:
        area = None
        print("Invalid shape type. Please specify either 'triangle' or 'rectangle'.")
    return area

shape_type = input("Enter the shape type, triangle or rectangle: ")
base_value = int(input("Enter the base value: "))
height_value = int(input("Enter the height value: "))
area = calculate_area(base_value, height_value, shape_type)
print("Area of the", shape_type, "is ", area)
Output
Enter the shape type, triangle or rectangle: triangle
Enter the base value: 10
Enter the height value: 5
Area of the triangle is  25.0


Enter the shape type, triangle or rectangle: rectangle
Enter the base value: 8
Enter the height value: 9
Area of the rectangle is  72
Answer