...

Using Python to Build a Calculator


Calculators date back to the 17th century, with the first calculator created in the form of a mechanical device. Over time, these calculators evolved so that more people could use them. It was in the 1960s, that the first electronic calculator came into being, and as time went on, the calculator was integrated into our computers and now mobiles.

Either physical or digital, we live in a time where each of us has used a calculator. Whether we are calculating rent, totalling the bill, or finding the final percentage of our kids’ results, we all have taken help from the calculator.

Let’s utilize Python basics, including functions, conditional statements, dictionaries, and loops, to create our version of a calculator.

Working of our Calculator

Our calculator will work as follows:

  1. It will ask the user for a number
  2. It will then ask the user for the operation
  3. It will ask the user for the second number
  4. It will perform its calculations and print the output
  5. It will ask the user if they want to carry on with this number (like our physical calculator) or start all over
  6. If the user asks to start all over, it will restart the above process
  7. If the user wants to carry on with the result, it will take this number as the first and ask for the operation, and then follow as the first time.

Let us construct the above thought process into a flowchart for better understanding:

Flowchart (Image by Author)

Defining Operation Functions

First of all, we will define functions that will be called when their corresponding operation symbol is selected by the user. We will define functions add for addition, subtract for subtraction, multiply for multiplication, and divide for division. These functions will take the two numbers as their input parameters, and perform the selected operation on them, and return the result.

def add(num1, num2):
    return num1 + num2


def subtract(num1, num2):
    return num1 - num2


def multiply(num1, num2):
    return num1 * num2


def divide(num1, num2):
    return num1/num2

Creating a Dictionary of Operations

Let us also create a dictionary of operations. The operation symbols will be stored as keys, and the name of the operation, that is also the name of the function, will be stored as the value to that key. We will ask the user to choose an operation, and based on their choice, the specific operation function that we have defined above will be called.

operations = {
    "+": add,
    "-": subtract,
    "*": multiply,
    "/": divide,
}

Asking User for Input

Once we have defined our functions, let us now ask the user for their first number num1, their selected operation operation_symbol, and their second number num2:

num1 = float(input("What is the first number?: "))
for symbol in operations:
            print(symbol)
operation_symbol = input("Pick an operation: ")
num2 = float(input("What is the next number?: "))

Notice that we have converted the input numbers to the float type. Also, we have created the for loop that will iterate over the keys in the operations dictionary we have defined earlier on, and print each operation symbol.

Calculating and Displaying the Answer

Next, is to calculate the answer and print it out to the user in its complete form. The following code will be used for this purpose:

answer = operations[operation_symbol](num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")

The answer variable will store the value that we have got from calling the relevant function, according to the operation symbol selected. We have used an f-string to properly format the output statement.

Check Calculator Continuity with the While Loop

Now that we have calculated and displayed the result, the next step is to check if the user wants to continue using the calculator by carrying on the result value answer onwards or wants to start the calculator all over. For this purpose, we will define a variable should_accumulate that will be True when the user wants to continue and will be False when the user does not want to continue, rather it will restart the calculator. The should_accumulate variable will be defined earlier in our code.

should_accumulate = True

while should_accumulate:
    ...
    choice = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ")

        if choice == "y":
            num1 = answer
        else:
            should_accumulate = False
            print("\n" * 20)
            

Since the should_accumulate variable is True, and we have added a while loop, the code within the loop will continue to run, unless the user selects ‘n’. When the user selects ‘n’, the calculation will not carry onwards, but will stop, and we will seemingly start a new console by typing 20 lines. But now we want to restart the calculator, so for this purpose, we will use a Python function concept called recursion.

For the calculator to restart, we will define it as a function, and it will be called when we want to restart the calculator function without carrying on the result. This will be coded as a recursive function. Recursion in Python allows a function to be called within itself, just like we will do below:

def calculator():
    should_accumulate = True
    num1 = float(input("What is the first number?: "))

    while should_accumulate:
        for symbol in operations:
            print(symbol)
        operation_symbol = input("Pick an operation: ")
        num2 = float(input("What is the next number?: "))
        answer = operations[operation_symbol](num1, num2)
        print(f"{num1} {operation_symbol} {num2} = {answer}")

        choice = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ")

        if choice == "y":
            num1 = answer
        else:
            should_accumulate = False
            print("\n" * 20)
            calculator()

Notice we have called the calculator function inside the calculator function itself. For the code to run for the first time, we need to call it outside.

Check out this link to access the complete code: https://github.com/MahnoorJaved98/Using-Python-to-Build-a-Calculator

Conclusion

In this short tutorial, we have successfully learned how to build a calculator in Python, with the ability to perform the basic 4 operations on addition, subtraction, multiplication and division. We have accomplished this using our basic knowledge of functions, loops, and recursive functions.

Source link

#Python #Build #Calculator