This article presents a straightforward Python program designed to calculate the area of a rectangle. It’s a great example for beginners to understand basic input, calculation, and output operations in Python.
Program Purpose
The purpose of this program is simple: to take two numerical inputs from the user, representing the length and width of a rectangle, and then compute and display its area. The area of a rectangle is calculated by multiplying its length by its width.
Program Code
Here is the complete Python code for the rectangle area calculator:
def calculate_rectangle_area():
"""
This function calculates the area of a rectangle based on user input
for length and width.
"""
print("Welcome to the Rectangle Area Calculator!")
try:
# Get input for length from the user
length_str = input("Please enter the length of the rectangle: ")
length = float(length_str) # Convert input to a floating-point number
# Get input for width from the user
width_str = input("Please enter the width of the rectangle: ")
width = float(width_str) # Convert input to a floating-point number
# Check if the inputs are positive
if length < 0 or width < 0:
print("Error: Length and width cannot be negative. Please enter positive values.")
else:
# Calculate the area
area = length * width
# Display the result
print(f"\nThe length of the rectangle is: {length}")
print(f"The width of the rectangle is: {width}")
print(f"The area of the rectangle is: {area:.2f}") # Format to 2 decimal places
except ValueError:
print("Error: Invalid input. Please enter numerical values for length and width.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Call the function to run the program
if __name__ == "__main__":
calculate_rectangle_area()