Objective
Develop a Python program that calculates the perimeter, area, and diagonal of a rectangle, given its width and height.
(Hint: use y = math.sqrt(x) to calculate a square root)
Example Python Exercise
Show Python Code
import math # Import the math module to use sqrt function
# Prompt the user for the width and height of the rectangle
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
# Calculate the perimeter, area, and diagonal
perimeter = 2 * (width + height)
area = width * height
diagonal = math.sqrt(width**2 + height**2) # Using Pythagoras' theorem to calculate diagonal
# Display the results
print(f"The perimeter of the rectangle is: {perimeter}")
print(f"The area of the rectangle is: {area}")
print(f"The diagonal of the rectangle is: {diagonal}")
Output
Case 1:
Enter the width of the rectangle: 5
Enter the height of the rectangle: 12
The perimeter of the rectangle is: 34.0
The area of the rectangle is: 60.0
The diagonal of the rectangle is: 13.0
Case 2:
Enter the width of the rectangle: 8
Enter the height of the rectangle: 15
The perimeter of the rectangle is: 46.0
The area of the rectangle is: 120.0
The diagonal of the rectangle is: 17.4642491965977
Share this Python Exercise