Python Program to Find the Area of a Rectangle Using a Class
Beginner · Classes and objects
This program defines a Rectangle class that stores a length and a breadth, with methods that work out the area and the perimeter. The area of a rectangle is length x breadth, and the perimeter is 2 x (length + breadth).
Program
Rectangle 8 x 5 Area: 40 Perimeter: 26 Is it a square? False Rectangle 6 x 6 Area: 36 Perimeter: 24 Is it a square? True
How it works
__init__stores the length and breadth inside each new object asself.lengthandself.breadth.area()andperimeter()use those stored values, so they are called with no arguments:selfis passed automatically.is_square()returnsTruewhen both sides are equal, as they are for the 6 x 6 rectangle.- The two objects come from one class but keep their own measurements, so one loop can report on both.
Another way to write it
Comparing rooms stored as objects
Bedroom: 14.0 square metres Kitchen: 7.5 square metres Hall: 27.0 square metres The biggest room is the Hall
Objects can be stored in a dictionary like any other value, and max() with a key function picks the room whose area is largest.
Try it yourself
Add a diagonal() method that returns (self.length ** 2 + self.breadth ** 2) ** 0.5.
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