26. Problem to calculate area of circle using class in Python

In this Python oops program, we will create a example to calculate area of circle using class in Python. This code demonstrates the basic functionality of the Circle class, allowing you to create circle objects, calculate their area and circumference, and retrieve the results.

Area of circle using class in Python

Steps to solve the program
  1. The code begins by importing the math module, which provides mathematical functions and constants.
  2. The class Circle is defined with a constructor method __init__. The constructor takes one parameter, radius, which represents the radius of the circle. Inside the constructor, the value of radius is assigned to the instance variable self.radius.
  3. The class also defines two additional methods: calculate_area and calculate_circumference. The calculate_area method calculates the area of the circle using the formula pi * radius^2, where pi is the mathematical constant pi (approximately 3.14159). The method returns the calculated area.
  4. The calculate_circumference method calculates the circumference of the circle using the formula 2 * pi * radius, and returns the result.
  5. An object of the Circle class is created by calling the constructor with the argument 10. The circle variable now refers to this object.
  6. The calculate_area method is called on the circle object and the result is stored in the area variable.
  7. The calculate_circumference method is called on the circle object and the result is stored in the circumference variable.
  8. The area and circumference are then printed using the print function.
				
					import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def calculate_area(self):
        return math.pi * self.radius**2
    
    def calculate_circumference(self):
        return 2 * math.pi * self.radius

# Create an object of the Circle class
circle = Circle(10)
area = circle.calculate_area()
circumference = circle.calculate_circumference()
print("Area:", area)
print("Circumference:", circumference)
				
			

Output:

				
					Area: 314.1592653589793
Circumference: 62.83185307179586
				
			

Related Articles

Create a Python class called Rectangle with attributes length and width.

Create a Python class called Person with attributes name and age.

Leave a Comment