Question

write a Python function to calculate the area and perimeter of the following rectangle, square, and triangle.

Answers

GPT-4o mini
Certainly! Below is a Python function that will calculate the area and perimeter for a rectangle, square, and triangle based on the provided dimensions.

```python
def calculate_area_perimeter(shape, *dimensions):
if shape == "rectangle":
if len(dimensions) != 2:
raise ValueError("Rectangle requires two dimensions: width and height.")
width, height = dimensions
area = width * height
perimeter = 2 * (width + height)
elif shape == "square":
if len(dimensions) != 1:
raise ValueError("Square requires one dimension: side length.")
side = dimensions[0]
area = side ** 2
perimeter = 4 * side
elif shape == "triangle":
if len(dimensions) != 3:
raise ValueError("Triangle requires three dimensions: the lengths of the sides.")
a, b, c = dimensions
# Using Heron's formula to calculate the area
s = (a + b + c) / 2 # semi-perimeter
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
perimeter = a + b + c
else:
raise ValueError(f"Unknown shape: {shape}")

return area, perimeter

# Example usage:
try:
# Rectangle with width=5 and height=10
rect_area, rect_perimeter = calculate_area_perimeter("rectangle", 5, 10)
print(f"Rectangle - Area: {rect_area}, Perimeter: {rect_perimeter}")

# Square with side=4
sq_area, sq_perimeter = calculate_area_perimeter("square", 4)
print(f"Square - Area: {sq_area}, Perimeter: {sq_perimeter}")

# Triangle with sides 3, 4, and 5
tri_area, tri_perimeter = calculate_area_perimeter("triangle", 3, 4, 5)
print(f"Triangle - Area: {tri_area}, Perimeter: {tri_perimeter}")

except ValueError as e:
print(e)
```

### Explanation:
1. **Function Definition**: The function `calculate_area_perimeter` takes the shape type as a string argument and the dimensions as a variable-length argument list.
2. **Shape Handling**: Depending on the shape specified (`rectangle`, `square`, or `triangle`), the function calculates the area and perimeter using appropriate formulas:
- **Rectangle**: Area = width × height; Perimeter = 2 × (width + height)
- **Square**: Area = side²; Perimeter = 4 × side
- **Triangle**: Area is calculated using Heron's formula; Perimeter = a + b + c
3. **Error Handling**: The function raises a `ValueError` if an unknown shape is specified or if the incorrect number of dimensions is provided for a shape.
4. **Example Usage**: The example uses the function with a rectangle, square, and triangle and prints the results.

Feel free to test and modify the function as per your needs!