by BehindJava

# Write a program to Create a Class which Performs Basic Calculator Operations in Python

Home » python » Write a program to Create a Class which Performs Basic Calculator Operations in Python

In this tutorial we are going to learn about Creating a Class which Performs Basic Calculator Operations in Python.

# Python Program to Create a Class which Performs Basic Calculator Operations

``````class cal():
def __init__(self,a,b):
self.a=a
self.b=b
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")

print()``````

# Program Explanation

1. A class called cal is created and the init() method is used to initialize values of that class.
2. Methods for adding, subtracting, multiplying, dividing two numbers and returning their respective results is defined.
3. The menu is printed, and the choice is taken from the user.
4. An object for the class is created with the two numbers taken from the user passed as parameters.
5. Using the object, the respective method is called according to the choice taken from the user.
6. When the choice is 0, the loop is exited.
7. The final result is printed.