Python Program to Find the Area of a Rectangle using Classes

In this Python program, we will create a class to calculate the area of a rectangle. We’ll define a class called Rectangle with methods to set the dimensions of the rectangle and calculate its area.

Problem Statement:

Write a Python program to find the area of a rectangle using classes. The program should take the length and width of the rectangle as input and output the calculated area.

Python Program to Find the Area of a Rectangle using Classes

class Rectangle:
    def __init__(self):
        self.length = 0
        self.width = 0

    def set_dimensions(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

def main():
    rectangle = Rectangle()
    
    length = float(input("Enter the length of the rectangle: "))
    width = float(input("Enter the width of the rectangle: "))
    
    rectangle.set_dimensions(length, width)
    area = rectangle.calculate_area()
    
    print(f"The area of the rectangle is: {area}")

if __name__ == "__main__":
    main()

How it Works:

  • We start by defining a class called Rectangle with an __init__ method to initialize the length and width to zero.
  • The class has two methods, set_dimensions and calculate_area.
    • set_dimensions takes the length and width as arguments and assigns them to the respective attributes of the class.
    • calculate_area calculates the area of the rectangle using the formula length * width and returns the result.
  • In the main function, we create an instance of the Rectangle class.
  • We take user input for the length and width of the rectangle.
  • We call the set_dimensions method to set the dimensions of the rectangle.
  • The calculate_area method is then called to calculate the area of the rectangle.
  • Finally, the calculated area is printed.

Input/Output:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...