Project Overview 💡
In this project, you'll create a Python program that calculates both the area and the perimeter of a rectangle using separate functions. This is a foundational exercise that helps reinforce the use of functions, arithmetic operations, and code organization.
Challenge Yourself! 🚀
Before checking the solution, try writing a program that calculates the area and perimeter of a rectangle using two different functions.
Task:
Write a Python program that:
Defines a function to calculate the area of a rectangle
Defines another function to calculate the perimeter
Calls both functions with sample inputs
Prints the results
Expected Output:
Below you can see what the program would output if we called it using the following input values:
area = rectangle_area(10, 3)
perimeter = rectangle_perimeter(10, 3)
As you can see, the program prints out 30 for the area and 26 for the perimeter.
Give it a shot! Scroll down when you're ready for the step-by-step guide.
Spoiler Alert!
Step-by-Step Guide
Step 1️⃣: Define the Area Function
Create a function that takes width
and height
as parameters and returns their product.
def rectangle_area(width, height):
return width * height
Step 2️⃣: Define the Perimeter Function
This function takes the same arguments and returns the sum of all sides.
def rectangle_perimeter(width, height):
return 2 * (width + height)
Step 3️⃣: Call the Functions with Example Values
Use example dimensions to call both functions and store the results.
area = rectangle_area(10, 3)
perimeter = rectangle_perimeter(10, 3)
Step 4️⃣: Print the Results
Display the area and perimeter on the screen.
print(area)
print(perimeter)
Complete Code 🧨
def rectangle_area(width, height):
return width * height
def rectangle_perimeter(width, height):
return 2 * (width + height)
# Calculate area and perimeter
area = rectangle_area(10, 3)
perimeter = rectangle_perimeter(10, 3)
# Display the results
print(area)
print(perimeter)
Alternative Solution
Here’s a version that takes input from the user instead of using hardcoded values:
def rectangle_area(w, h):
return w * h
def rectangle_perimeter(w, h):
return 2 * (w + h)
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
print("Area:", rectangle_area(width, height))
print("Perimeter:", rectangle_perimeter(width, height))
Comparison
The original version is quick and great for testing or learning.
The alternative version adds interactivity by allowing users to input their own dimensions.
Want More? 🔥
Enjoyed this project? Unlock real-world projects with full guides & solutions by subscribing to the paid plan. 🎉