Sunday, October 20, 2024

Write Python Program using different techniques

Write Python Program using different techniques

We can write Python Program using different techniques. Every technique has its own advantages and disadvantages.

Python program is written using different techniques to solve the problem where radius is given and need to calculate the Area of the circle. 

Method 1: Using only main program. Here PI constant and r variable

PI=22/7
r=int(input("Enter a radius of the Circle? "))
print("Area of the Circle =" , PI*r*r)
r=int(input("Enter a radius of the Circle? "))
print("Area of the Circle =" , PI*r*r)

Sample Output
Enter a radius of the Circle? 7
Area of the Circle = 154.0
Enter a radius of the Circle? 14
Area of the Circle = 616.0

Method 2: the Procedure CirlceArea(r) is used to calculate the Area. here r is parameter

PI=22/7

def CirlceArea(r):
    print("Area of the Circle =" , PI*r*r)

r=int(input("Enter a radius of the Circle? "))
CirlceArea(r)
r=int(input("Enter a radius of the Circle? "))
CirlceArea(r)

Method 3: The function CirlceArea(r) is used. Here r is parameter. Function return the output as string. When we call the function value is given

PI=22/7

def CirlceArea(r):
    return f"Area of the Circle ={PI*r*r}"  

r=int(input("Enter a radius of the Circle? "))
print(CirlceArea(r))
r=int(input("Enter a radius of the Circle? "))
print(CirlceArea(r))

Method 4: MyCircle is used as class. Here PI is a constant and GetR(self,rr), CirlceArea(self) are methods. C1,C2 are objects in main program

class MyCircle:
    PI=22/7
    
    def GetR(self,rr):
        self.r=rr
    
    def CirlceArea(self):
        print("Area of the Circle =" , self.PI*(self.r*self.r))

r=int(input("Enter a radius of the Circle? "))
C1=MyCircle()
C1.GetR(r)
r=int(input("Enter a radius of the Circle? "))
C2=MyCircle()
C2.GetR(r)
C1.CirlceArea()
C2.CirlceArea()

Method 5: Instead if GetR(self,rr) method constructor is used. When we create the object constructor is called automatically

class MyCircle:
    PI=22/7
    
    def __init__(self,rr):
        self.r=rr
    
    def __str__(self):
        return f"Area of the Circle ={ self.PI*(self.r*self.r)}"

r=int(input("Enter a radius of the Circle? "))
C1=MyCircle(r)
r=int(input("Enter a radius of the Circle? "))
C2=MyCircle(r)
print(C1)
print(C2)

No comments:

Post a Comment