Editor

Python Program to Find the Area and Perimeter of a Rectangle

Beginner · Basics

The area of a rectangle is the space inside it, length x width, and the perimeter is the distance all the way round it, 2 x (length + width). This program works out both for a rectangle with given sides.

Program

area_and_perimeter_of_rectangle.py
length = 12 # in m; or: length = float(input("Enter the length: "))
width = 8 # in m; or: width = float(input("Enter the width: "))
area = length * width
perimeter = 2 * (length + width)
print("Length:", length, "m")
print("Width:", width, "m")
print("Area:", area, "square m")
print("Perimeter:", perimeter, "m")
if length == width:
print("All sides are equal, so this rectangle is a square")
Output
Length: 12 m
Width: 8 m
Area: 96 square m
Perimeter: 40 m

How it works

  1. length * width gives the area, measured in square units because two lengths are multiplied.
  2. 2 * (length + width) gives the perimeter, since a rectangle has two lengths and two widths.
  3. The brackets matter: 2 * length + width would add only one width.
  4. The last check spots a square, the special rectangle whose length equals its width.

Other ways to write it

With the diagonal

With the diagonal
import math
length, width = 12, 5
diagonal = math.sqrt(length ** 2 + width ** 2) # Pythagoras
print("Area:", length * width)
print("Perimeter:", 2 * (length + width))
print("Diagonal:", diagonal)
Output
Area: 60
Perimeter: 34
Diagonal: 13.0

The diagonal splits the rectangle into two right-angled triangles, so Pythagoras gives its length: 13 for a 12 by 5 rectangle.

A function that returns two values

A function that returns two values
def rectangle(length, width):
return length * width, 2 * (length + width)
for l, w in [(12, 8), (5, 5), (7.5, 2)]:
area, perimeter = rectangle(l, w)
print(f"{l} x {w}: area = {area}, perimeter = {perimeter}")
Output
12 x 8: area = 96, perimeter = 40
5 x 5: area = 25, perimeter = 20
7.5 x 2: area = 15.0, perimeter = 19.0

A Python function can return two values at once, and area, perimeter = ... unpacks them into two variables.

Try it yourself

Work out the cost of fencing the rectangle at Rs 150 per meter of perimeter.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises