Exercise
Perimeter And Area
Objective
Develop a Python program to calculate the perimeter, area, and diagonal of a rectangle from its width and height (perimeter = sum of the four sides, area = base x height, diagonal using the Pythagorean theorem). It must repeat until the user enters 0 for the width.
Example Python Exercise
Show Python Code
import math
# Repeat until the user enters 0 for the width
while True:
# Prompt the user for the width and height
width = float(input("Enter the width of the rectangle (0 to stop): "))
# If the width is 0, exit the loop
if width == 0:
break
height = float(input("Enter the height of the rectangle: "))
# Calculate the perimeter (sum of all sides)
perimeter = 2 * (width + height)
# Calculate the area (width * height)
area = width * height
# Calculate the diagonal using the Pythagorean theorem
diagonal = math.sqrt(width**2 + height**2)
# Display the results
print(f"Perimeter: {perimeter}")
print(f"Area: {area}")
print(f"Diagonal: {diagonal}")
print() # Blank line for better readability
Output
Enter the width of the rectangle (0 to stop): 3
Enter the height of the rectangle: 4
Perimeter: 14.0
Area: 12.0
Diagonal: 5.0
Enter the width of the rectangle (0 to stop): 5
Enter the height of the rectangle: 12
Perimeter: 34.0
Area: 60.0
Diagonal: 13.0
Enter the width of the rectangle (0 to stop): 0
Share this Python Exercise