Write a Python program to create a class representing a Circle. Include methods to calculate its area and perimeter.
Plain code approach
In the above exercise we create a “Person” class with properties for name, age, and country. It includes a method to display the person’s details.
Finally it creates two instances of the Person class and displays their details using the displayDetails() method.
Solution:
# Import the math module to access mathematical functions like piimportmath# Define a class called Circle to represent a circleclassCircle:# Initialize the Circle object with a given radiusdef__init__(self,radius):self.radius=radius# Calculate and return the area of the circle using the formula: π * r^2defcalculate_circle_area(self):returnmath.pi*self.radius**2# Calculate and return the perimeter (circumference) of the circle using the formula: 2π * rdefcalculate_circle_perimeter(self):return2*math.pi*self.radius# Example usage# Prompt the user to input the radius of the circle and convert it to a floating-point numberradius=float(input("Input the radius of the circle: "))# Create a Circle object with the provided radiuscircle=Circle(radius)# Calculate the area of the circle using the calculate_circle_area methodarea=circle.calculate_circle_area()# Calculate the perimeter of the circle using the calculate_circle_perimeter methodperimeter=circle.calculate_circle_perimeter()# Display the calculated area and perimeter of the circleprint("Area of the circle:",area)print("Perimeter of the circle:",perimeter)
Sample output
Input the radius of the circle: 4
Area of the circle: 50.26548245743669
Perimeter of the circle: 25.132741228718345