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
Length: 12 m Width: 8 m Area: 96 square m Perimeter: 40 m
How it works
length * widthgives the area, measured in square units because two lengths are multiplied.2 * (length + width)gives the perimeter, since a rectangle has two lengths and two widths.- The brackets matter:
2 * length + widthwould add only one width. - The last check spots a square, the special rectangle whose length equals its width.
Other ways to write it
With the diagonal
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
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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises