Jima Victor
webcodespace

webcodespace

How to make a simple calculator in python

How to make a simple calculator in python

Jima Victor's photo
Jima Victor
·Aug 23, 2022·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Functionality of the Calculator App
  • Asking the user to select an operation
  • Storing the user's selected operation and operands
  • Computing the result
  • Displaying the result
  • Asking the user if they want to perform another operation.

Building out a calculator app in python is one of those beginner projects that is really going to help you improve your skills. As a beginner, building out projects is the best way to learn.

It doesn't matter how much you have read or studied in programming if you don't build out projects.

Building projects helps you reinforce and better retain and understand whatever you have read.

So in this tutorial, we are going to be building out a simple calculator app in python - nothing complex.

Objective: By the end of this tutorial, you must have learnt how to build a simple calculator that can add, subtract, divide, and multiply two numbers.

Let's begin...

Functionality of the Calculator App

This is a step-by-step rundown of what the calculator app would do. This includes:

  1. Asking the user to select an operation
  2. Storing the user's selected operation and operands
  3. Computing the result
  4. Displaying the result
  5. Asking the user if they want to perform another operation.

Asking the user to select an operation

To ask the user to select an operation, we make use of five print statements - One for the instruction and the others to display the options for addition, subtraction, multiplication and division respectively.

    print("Select operation: ")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

Storing the user's selected operation and operands

So after asking the user to select an operation, we need to store their selection in our program; so we can be able to determine whether they want to add, subtract, multiply or divide. We also need to store the two operands they want to carry out the operation on. To do this in python, we use the following code:

    operation = int(input("Choose operation(1/2/3/4): "))
    first_operand = int(input("Enter first number: "))
    second_operand = int(input("Enter second number: "))

So we have three variables to store the operation, the first operand and the second operand. And if you'd notice, we also made use of the int() method to convert the user input into integer; this is because the user input is by default a string and we do not want that.

Computing the result

In order to compute the result we are going to create a function in python to handle the computation as follows:

def compute(first_operand, second_operand, operation):
    match operation:
        case 1:
            return (first_operand + second_operand)
        case 2:
            return (first_operand - second_operand)
        case 3:
            return (first_operand * second_operand)
        case 4:
            return (first_operand / second_operand)
        case _:
            return "Invalid selection"

So the above compute function takes the first operand, the second operand and the operation to be performed as parameters. We are then going to match the operation to either 1, 2, 3, or 4 to determine the kind of operation to be performed.

Remember when we asked our user to select an operation, we attached the choice of 1 to addition, 2 to subtraction, 3 to multiplication and 4 to division.

So if the user chooses 1, case 1 of the compute function is going to run and the function is going to return the sum of the two operands. Likewise if the user chooses 2, case 2 of the compute function is going to run and the function will return the difference between the first operand and the second operand. A similar thing is going to happen if the user chooses 3 or 4.

However, if the user enters anything other than 1, 2, 3 or 4, the program will continue by taking the two operands but then it's going to print out "invalid selection" as our result.

Displaying the result

In order to display the result, we make use of the print statement and then convert into string the return value of the compute function so we can then concatenate it with "result: ". The reason for this conversion is because python doesn't allow us to concatenate a string with an integer. This is the code:

    print("result: " + str(compute(first_operand, second_operand, operation)))

Asking the user if they want to perform another operation.

So for this step, this is the line of code we would use:

    calculate_again = input("Do you wish to perform another calculation? (yes/no)").lower()

So this line is really simple, the user can reply with a yes or no and we are going to store it in the calculate_again variable. But before we store it in, we are going to convert it to lowercase using the lower() method; so that if the user types in "YES" or "Yes" or "yEs", it's all going to be stored in as "yes" in our program.

After storing this into a variable, the next thing we will do, is to use whatever the user have entered, to determine whether we would continue the program or not. To do this, we'll make use of the if...else statement in python.

    if(calculate_again == "no"):
        break
    elif(calculate_again == "yes"):
        continue
    else:
        print("invalid input")

So from the above code, if the user enters a "no", we will end the program, if they enter a "yes", we will continue with another operation and every other thing other than a yes or a no will cause our program to print "invalid input" to the console.

Now if you noticed, we made use of the break and continue statements in our if...else block and these statements are only meant to be used in parts of our code that are loops or some sort.

So to finish off, we are going to add all our code aside from the compute function into a while loop so it can keep running operations for the user until they wish to end the program by replying with a "no" to "Do you wish to perform another calculation?"

So our entire code is going to look like this now:

def compute(first_operand, second_operand, operation):
    match operation:
        case 1:
            return (first_operand + second_operand)
        case 2:
            return (first_operand - second_operand)
        case 3:
            return (first_operand * second_operand)
        case 4:
            return (first_operand / second_operand)
        case _:
            return "Invalid selection"

    while True:
        print("Select operation: ")
        print("1. Add")
        print("2. Subtract")
        print("3. Multiply")
        print("4. Divide")

        operation = int(input("Enter choice(1/2/3/4): "))
        first_operand = int(input("Enter first number: "))
        second_operand = int(input("Enter second number: "))

        print("result: " + str(compute(first_operand, second_operand, operation)))

        calculate_again = input("Do you wish to perform another calculation? (yes/no)").lower()

        if(calculate_again == "no"):
            break
        elif(calculate_again == "yes"):
            continue
        else:
            print("invalid input")
 
Share this