codescracker
python

Python Program to Make Calculator



« Previous Program Next Program »

In this article, I've created some programs in Python, to make a simple calculator. Here are the list of calculator programs in Python:

Calculator Program using while Loop and if-else

This program makes a simple calculator in Python that performs four basic mathematical operations such as add, subtract, multiply, and divide two numbers entered by user. Here I've provided 5 options to user, the fifth option is to exit.

# ----codescracker.com----

while True:
   print("1. Addition")
   print("2. Subtraction")
   print("3. Multiplication")
   print("4. Division")
   print("5. Exit")
   print("Enter Your Choice (1-5): ", end="")
   ch = int(input())
   if ch>=1 and ch<=4:
      print("\nEnter Two Numbers: ", end="")
      numOne = float(input())
      numTwo = float(input())
   if ch==1:
      res = numOne + numTwo
      print("\nResult =", res)
   elif ch==2:
      res = numOne - numTwo
      print("\nResult =", res)
   elif ch==3:
      res = numOne * numTwo
      print("\nResult =", res)
   elif ch==4:
      res = numOne / numTwo
      print("\nResult =", res)
   elif ch==5:
      break
   else:
      print("\nInvalid Input!..Try Again!")
   print("------------------------")

Here is the initial output produced by this Python program of simple calculator:

python make calculator

Now supply the input. For example type 1 as choice, and press ENTER key, here is the output you'll see:

python calculator

Now enter any two numbers say 32 as first, press ENTER and 44 as second number, again press ENTER. Here is the output you'll see, that shows the result and again options gets displayed to operator further:

calculator program python

To exit, type 5 as choice and press ENTER. The program execution gets terminated like shown in the snapshot given below:

calculator code python

The dry run of above program goes like:

Modified Version of Previous Program

This program is the modified version of previous program. This program uses try-except to handle invalid inputs. That is, when user enters any invalid input like c, # as number, then program raises (prints) error message and continue asking to enter the valid one. Let's have a look:

# ----codescracker.com----

print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
while True:
   while True:
      print("Enter Your Choice (1-5): ", end="")
      try:
         ch = int(input())
         if ch>=1 and ch<=4:
            print("\nEnter Two Numbers: ", end="")
            numOne = float(input())
            numTwo = float(input())

         if ch==1:
            print("\nResult =", numOne+numTwo)
         elif ch==2:
            print("\nResult =", numOne-numTwo)
         elif ch==3:
            print("\nResult =", numOne*numTwo)
         elif ch==4:
            print("\nResult =", numOne/numTwo)
         elif ch==5:
            break
         else:
            print("\nInvalid Input!..Try Again!")
         print("------------------------")
      except ValueError:
         print("\nInvalid Input!..Try Again!")
         print("------------------------")
         continue
   if ch==5:
      break

Here is its sample run with user input 3 as choice, then 2 and 5 as two numbers:

python make calculator

As you can see from above sample run, the menu is displayed only once. Later on, I've only displayed the message that asks to enter the choice to continue the operation. Here is continued sample run with invalid and valid inputs:

python make simple calculator

The only way to exit the program, is by using 5 as choice.

Note - In above program, when user enters invalid input, then program flow goes to except ValueError's body and prints an error message. Then using continue keyword, program flow goes to the initial (first) statement of while loop's body to receive the input again inside try

Calculator Program using Function

This program is created using four user-defined functions. All functions receives two arguments and returns the corresponding result.

# ----codescracker.com----

def add(a, b):
   return a+b
def sub(a, b):
   return a-b
def mul(a, b):
   return a*b
def div(a, b):
   return a/b

print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
while True:
   while True:
      print("Enter Your Choice (1-5): ", end="")
      try:
         ch = int(input())
	
         if ch>=1 and ch<=4:
            print("\nEnter Two Numbers: ", end="")
            nOne = float(input())
            nTwo = float(input())

         if ch==1:
            print("\nResult =", add(nOne, nTwo))
         elif ch==2:
            print("\nResult =", sub(nOne, nTwo))
         elif ch==3:
            print("\nResult =", mul(nOne, nTwo))
         elif ch==4:
            print("\nResult =", div(nOne, nTwo))
         elif ch==5:
            break
         else:
            print("\nInvalid Input!..Try Again!")
         print("------------------------")

      except ValueError:
         print("\nInvalid Input!..Try Again!")
         print("------------------------")
         continue
   if ch==5:
      break

This program produces same output as of previous program.

Calculator Program using Class

This is the last calculator program in Python, created using class. To access member function of a class, an object is required. Therefore an object ob is created of a class named CodesCracker, of which I've to access member functions using dot (.) operator.

# ----codescracker.com----

class CodesCracker:
   def add(self, a, b):
      return a+b
   def sub(self, a, b):
      return a-b
   def mul(self, a, b):
      return a*b
   def div(self, a, b):
      return a/b

print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

while True:
   while True:
      print("Enter Your Choice (1-5): ", end="")

      try:
         ch = int(input())

         if ch>=1 and ch<=4:
            print("\nEnter Two Numbers: ", end="")
            nOne = float(input())
            nTwo = float(input())
            ob = CodesCracker()

         if ch==1:
            print("\n" +str(nOne)+ " + " +str(nTwo)+ " = " + str(ob.add(nOne, nTwo)))
         elif ch==2:
            print("\n" +str(nOne)+ " - " +str(nTwo)+ " = " + str(ob.sub(nOne, nTwo)))
         elif ch==3:
            print("\n" +str(nOne)+ " * " +str(nTwo)+ " = " + str(ob.mul(nOne, nTwo)))
         elif ch==4:
            print("\n" +str(nOne)+ " / " +str(nTwo)+ " = " + str(ob.div(nOne, nTwo)))
         elif ch==5:
            break
         else:
            print("\nInvalid Input!..Try Again!")
         print("------------------------")

      except ValueError:
         print("\nInvalid Input!..Try Again!")
         print("------------------------")
         continue

   if ch==5:
      break

Here is its sample run with some user inputs:

calculator program in python

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker