Python Program to Create a Class and Compute the Area and the Perimeter of the Circle
In this example, we will write a python program to find the area and perimeter of the circle using class and objects. To better understand this example, make sure you have knowledge of the following tutorials:-
Python Program to Create a Class and Compute the Area and the Perimeter of the Circle
import math class Circle: def __init__(self, radius): self.radius = radius def area(self): return math.pi * (self.radius ** 2) def perimeter(self): return 2 * math.pi * self.radius r = int(input("Enter radius of circle: ")) obj = Circle(r) print("Area of circle:", round(obj.area(), 2)) print("Perimeter of circle:", round(obj.perimeter(), 2))
The output of the above program is:-
Enter radius of circle: 4
Area of circle: 50.27
Perimeter of circle: 25.13
Area of circle: 50.27
Perimeter of circle: 25.13
Program Explanation
Here we have created a class named “Circle” that has an attribute radius. The constructor of the class initiates the attribute using the __init__ function. Two methods “area” and “perimeter” are created to calculate the area of the given circle. We need math library to get the value of PI, so it is imported at the top of the program. Once the class has been defined, we take input from the user as a radius of the circle. An instance of the class “Circle” is created as “obj” and the method is invoked to display the result.