by BehindJava
Write a program to Create a Class and Compute the Area and the Perimeter of the Circle in Python
In this tutorial we are going to learn about creating a Class and Compute the Area and the Perimeter of the Circle in Python.
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))
Program Explanation
- User must enter the value of radius.
- A class called circle is created and the init() method is used to initialize values of that class.
- A method called as area returns math.pi*(self.radius**2) which is the area of the class.
- Another method called perimeter returns 2math.piself.radius which is the perimeter of the class.
- An object for the class is created.
- Using the object, the methods area() and perimeter() are called.
- The area and perimeter of the circle is printed.