Write A Python Class Named Rectangle Constructed By A Length And Width

Hi in this article let's construct a class name that does rectangle with the class members as  to variables Length and width of rectangle.  Once we have Length and width of the rectangle, let's try to find the area of a rectangle and print  it on  standard output.

Let's use Python class to define the class and computer the area of a rectangle. 


 

Write A Python Class Named Rectangle Constructed By A Length And Width

 


Write A Python Class Named Rectangle Constructed By A Length And Width

Define a class name as a rectangle, modify the default constructor having two variables Length and width,  the Length and width are floating type variables use the input function call to ask a user to enter the length and width of the rectangle.

Inside the class define a function named as area,  take a new variable named as result and compute the multiplication of Length and width.  Once the area is computed, use the print statement to print the area of a rectangle as shown below.

class rectangle:

   def __init__(self):
       self.length = float(input("Enter Rectangle Length : "))
       self.width = float(input("Enter Rectangle Width : "))

   def area(self):
       result = self.length * self.width
       print("Area of Rectangle is : %.2f" %result)






In the main program take a rectangle object and  call the rectangle constructor as shown below,  once  we get the rectangle object call the area() function to display the area of a rectangle  on standard output.

rectangle_obj = rectangle()
rectangle_obj.area()





Python Script
==========================

class rectangle:

   def __init__(self):
       self.length = float(input("Enter Rectangle Length : "))
       self.width = float(input("Enter Rectangle Width : "))

   def area(self):
       result = self.length * self.width
       print("Area of Rectangle is : %.2f" %result)


rectangle_obj = rectangle()
rectangle_obj.area()




Output
===================
Enter Rectangle Length : 23.3333
Enter Rectangle Width : 22.1121333333333333333
Area of Rectangle is : 515.95




Output
=====================
Enter Rectangle Length : 12
Enter Rectangle Width : 90.78
Area of Rectangle is : 1089.36




Conclusion
==================
Execute the above Python program by providing floating point integer variables as length and width of the rectangle,  then not down the area of a rectangle.

Comment it down if you find any problem  with the above Python program.



Post a Comment

0 Comments