top of page

Calculating Areas and Parameters Of Different Shapes Using Python


1. Rectangle

class Shape:
    '''A class defining shapes'''
    def __repr__(self):
        return f'I am a {self.__class__.__name__}' #print the shape's name

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        
    def area(self):
        A = self.width*self.height
        return A
        pass
    
    def perimeter(self):
        P = 2*(self.width+self.height)
        return P
        pass
    
rectangle = Rectangle(3, 4)

print(rectangle)
print("area =", rectangle.area())
print("perimeter =",rectangle.perimeter())

I am a Rectangle area = 12 perimeter = 14


2. Square

class Shape:
    '''A class defining shapes'''
    def __repr__(self):
        return f'I am a {self.__class__.__name__}' #print the shape's name

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.height = self.width 
        
class Square(Rectangle):
    def area(self):
        A = self.width*self.height
        return A
        pass
    def perimeter(self):
        P = 2*(self.width+self.height)
        return P
        pass

square = Square(5,5)

print(square)
print("area =", square.area())
print("perimeter =",square.perimeter())

I am a Square area = 25 perimeter = 20


3. Circle

import math

class Shape:
    '''A class defining shapes'''
    def __repr__(self):
        return f'I am a {self.__class__.__name__}' 

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        A = math.pi * self.radius ** 2
        return A

    def perimeter(self):
        P = 2 * math.pi * self.radius
        return P

circle = Circle(5)

print(circle)
print("area =", round(circle.area(),2))
print("perimeter =",round(circle.perimeter(),2))

I am a Circle area = 78.54 perimeter = 31.42




















Recent Posts

See All
Sorting Algorithms in Python

1. Selection sort Method 1 def selectionSort(array): n = len(array) for i in range(n): # Initially, assume the first element of the...

 
 
 
Search Algorithms in Python

1. Binary search def binary_search(data, target, low, high): if low > high: return False else: mid = (low+high)//2 if target ==...

 
 
 

Comments


bottom of page