Python Program to Build a Calculator using OOP

python programs

Problem: Write a Python program to create a simple calculator i.e a calculator with addition, subtraction, multiplication, and division functionality using object-oriented programming (OOP).

To create a basic calculator in python we first need to create a class and define different functionalities like addition, subtraction, etc into separate methods.

After that, we will ask the user to choose what functionality they want to execute through an input, then the user will input the required variables and the respective function will be called to compute the result.

Let’s try to implement it in python.

Prerequisites:

  1. functions using def in Python
  2. Python’s If and else
  3. While loop

Source Code:

class Calculator:
    def add(self, a, b):
        return a+b
    
    def subtract(self, a, b):
        return a-b
        
    def multiply(self, a, b):
        return a*b

    def divide(self, a, b):
        return a/b

#create a calculator object
my_cl = Calculator()

while True:

    print("1: Add")
    print("2: Subtract")
    print("3: Multiply")
    print("4: Divide")
    print("5: Exit")
    
    ch = int(input("Select operation: "))
    
    #Make sure the user have entered the valid choice
    if ch in (1, 2, 3, 4, 5):
        
        #first check whether user want to exit
        if(ch == 5):
            break
        
        #If not then ask fo the input and call appropiate methods        
        a = int(input("Enter first number: "))
        b = int(input("Enter second number: "))
        
        if(ch == 1):
            print(a, "+", b, "=", my_cl.add(a, b))
        elif(ch == 2):
            print(a, "-", b, "=", my_cl.subtract(a, b))
        elif(ch == 3):
            print(a, "*", b, "=", my_cl.multiply(a, b))
        elif(ch == 4):
            print(a, "/", b, "=", my_cl.divide(a, b))
    
    else:
        print("Invalid Input")

Output:

calculator in python

In the above program we have used OOP (i.e class and object) to create a basic python calculator.

Make sure that you typecast the inputs into an integer before using them and also check for invalid inputs prior to calling appropriate methods.

If you have any doubts or suggestions then please comment below.

4 thoughts on “Python Program to Build a Calculator using OOP”

    1. Add the following function in the class:

      def modulus(self, a, b):
              return a%b

      and option 5 in the if-clause:

      elif(ch == 4):
                  print(a, "/", b, "=", my_cl.divide(a, b)

Leave a Reply

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