Simple calculator program using Python3

In this post we are going to learn how to use Python’s while loop, if conditioning, break, taking input from user.

Well that seems a lot, but its all simple when you look at the program.

#subroutine to calculate addition and subtraction by taking user choice as input
 def operate(o):
     #convert user input into integer
     a = int(input("enter first number "))
     b = int(input("enter second number "))
     if(o == "a"):
         return a+b
     elif(o == "s"):
         return a-b
 #execution starts from here
 operation = input("Enter your choice: ")
 total = 0
 while(operation!=""):
     if(operation == "a"):
         print("you choose addition")
         total = operate(operation)
     elif(operation == "s"):
         print("you choose substraction")
         total = operate(operation)
     else:
         print("you choose nothing")
     #print the actual result
     print("Result = ",total)
     #choice of user which decided whether to continue or not
     choice = input("Do you want to continue?Type Y to continue or any other key to quit: ")
     if(choice == "y"):
         operation = input("Enter your choice: ")
     else:
         break

For easier understanding let me explain it to you in the form of algorithm.

  • Execution starts from asking user the input.
  • Then using if condition we check what type of operation the user has chosen.
  • Then according to the operation we call the subroutine and result is returned.
  • At the end we ask the user once more if the user wants to continue or exit.

If any doubts or needed clarifications don’t forget to comment.

Leave a Reply

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