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

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!
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.
SHARE Python Program to Create a Class which Performs Basic Calculator Operations

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share