Python Program to Create a Class which Performs Basic Calculator Operations
In this example, we will write a python program to create a basic calculator using class and objects. To better understand this example, make sure you have knowledge of the following tutorials:-
Python Program to Create a Class which Performs Basic Calculator Operations
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
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 = Calculator(a, b)
choice = 1
while choice != 0:
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("0. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
print("Result: ", obj.add())
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!!")The output of the above program is:-
Enter first number: 1
Enter second number: 4
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 1
Result: 5
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 4
Result: 0.25
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 0
Exiting!
Enter second number: 4
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 1
Result: 5
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 4
Result: 0.25
1. Add
2. Subtraction
3. Multiplication
4. Division
0. Exit
Enter choice: 0
Exiting!
Program Explanation
Here we have created a class named “Calculator” that has two attributes a and b. The constructor of the class initiates these two attributes using __init__ function. Four methods are created to perform basic calculation operations viz. add, multiply, divide and subtract. Once the class has been defined, we take inputs from the user as a and b where a is the first number and b is the second number. An instance of the class “Calculator” is created as “obj”. A variable choice is defined to iterate through while loop and show menu for the user that takes values from 0 to 4, where 0 is for exit case.
