Step-by-Step Guide to Building a Calculator with Python

Step-by-Step Guide to Building a Calculator with Python

A guide on building a simple calculator with python.

Almost everyone is conversant with calculators. A calculator is a device that enables a user to perform mathematical calculations easily. It takes away the burden of having to do all mathematical calculations manually which could consume more time.

In this tutorial, we will be exploring the step-by-step process of building a calculator with Python programming language.

What we will be Building

The calculator we will be building will ask the user to enter a number, next it will prompt the user to choose an operation that will be performed and lastly, it will ask the user to select the next number for the operation to be executed.

Once the operation is executed, the result will be displayed. The calculator will ask the user if they want to continue solving using the answer they got or if they want to exit the calculator.

If the user chooses to continue, the calculator repeats the process using the answer as the starting number. If the user chooses exits, the calculator exits.

Prerequisites

To follow along in this tutorial, you’ll need to have the following:

  • A code editor - This tutorial uses a VSCode editor (But every other code editor works fine too)

  • Python installed - This tutorial uses Python 3

  • Knowledge of the Python programming language

Defining Arithmetic Functions

In this section, we will focus on defining arithmetic functions that lay the foundation for the calculator's mathematical capabilities. By carefully crafting these functions, we will enable our calculator to add, subtract, multiply, and divide numbers precisely and accurately.

To begin, create a main.py file and import the os module. This will allow us to interact with the operating system and clear the screen at the end of our program.

import os

Next, add the following line of code to prompt the calculator to print a welcome message when the user begins calculating for the first time:

print("Welcome to my calculator")

Now to enable our calculator to perform basic arithmetic operations like addition, subtraction, multiplication, and division; we need to define each of the arithmetic functions like so:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

From the code above, the add function is defined and it takes two arguments x and y. Next, it returns the result by adding x and y. This is also the same for the subtraction - and multiplication * functions.

I know you might be wondering why a division function is not part of the code above, you don’t need to worry, we will implement it too. But, taking hold of the division function is quite a tricky one. This is because no number is divisible by zero and if the user inputs zero as the second argument, the user should get an error message that says “Cannot divide by zero”. To implement this in the calculator we make use of an if-else condition.

First, we will define a function divide that takes in two arguments x and with the code snippet below:

def divide(x, y):

Then we add the following code inside the divide function:

if y != 0:
        return x / y
    else:
        raise ValueError("Cannot divide by zero.")

This will check if the second argument y is not equal to zero (y != 0). If the condition is true, the code proceeds to the next line and it returns the result of dividing x by y.

If the condition is false, the else condition is prompted and a valueError is raised using the raise statement, and the error message "Cannot divide by zero." is prompted to the user.

Creating the Operation Dictionary

The next step after defining each arithmetic function is to create a dictionary that holds all arithmetic operations to be used in the calculator. The dictionary will take all the operation symbols as the keys and their corresponding arithmetic functions as the values. Assign this dictionary to a variable called operation using the following code:

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

Implementing the Calculator Logic

Now that we have created the operation dictionary to define each arithmetic function, it’s time to implement the calculator logic. We will create a calculator program that repeatedly prompts the user for input, performs arithmetic calculations based on the chosen operation, and display the calculated results. This program will also handle invalid input and exceptions to provide a functional calculator experience.

To achieve this, add the following code below the operation dictionary:

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

This will define a function named calculator and will do the following:

  1. Prompt the user to enter the first number by displaying the message "What is the first number?" using the input() function.

  2. Convert the entered value to a floating number using the float() function and store it in variable num1.

  3. Set the variable repeat to True, indicating that the calculator program should continue running.

Add the following code snippet to create a while loop that allows the user to perform multiple arithmetic calculations using the calculator:

while repeat:
        choice = input("Enter your choice ('+', '-', '*', or '/'):\\n ")
        num2 = float(input("What is the next number?\\n"))

Here’s an explanation of what the code above does:

  1. The code enters a while loop with the condition repeat, which was initialized earlier.

  2. Within the loop, the user is prompted to enter a choice of arithmetic operation, such as addition (+), subtraction (-), multiplication (*), or division (/), using the input() function. The choice entered is then stored in the variable choice.

  3. The user is then asked to input the next number for the calculation using the input() function. The entered value is converted to a floating number using the float() function and stored in the variable num2.

  4. The loop continues as long as repeat evaluates to True, allowing the user to perform multiple calculations without exiting the program.

Now, perform the arithmetic calculation based on the user's chosen operation by adding the following code snippets:

if choice in operation:
            try:
                answer = operation[choice](num1, num2)
                print(f"{num1} {choice} {num2} = {answer}")
            except ValueError as e:
                print("Error:", str(e))
                break
        else:
            print("Invalid input. Please try again.")
            continue

The code above will do the following:

  1. Check if the choice variable is one of the valid operations stored in the operation dictionary.

  2. Check if the choice matches one of the valid operations, and if it does the code enters a try block to perform the calculation using the selected operation. It calls the function corresponding to the chosen operation with the operands num1 and num2 and stores the result variable answer.

  3. Prints the calculated result to the console in the format {num1} {choice} {num2} = {answer}.

  4. Captures the exception using the except block in cases where a ValueError exception occurs during the calculation (e.g., division by zero), prints an error message, and then breaks out of the loop.

  5. Prints an "Invalid input" message If the choice is not one of the valid operations, and continues to the next iteration of the loop.

In total, the complete function at this point is expected to look like the following:

def calculator():
    num1 = float(input("What is the first number?\\n"))
    repeat = True
        while repeat:
        choice = input("Enter your choice ('+', '-', '*', or '/'):\\n ")
        num2 = float(input("What is the next number?\\n"))
                if choice in operation:
            try:
                answer = operation[choice](num1, num2)
                print(f"{num1} {choice} {num2} = {answer}")
            except ValueError as e:
                print("Error:", str(e))
                break
        else:
            print("Invalid input. Please try again.")
            continue

Clearing the Console Screen

We have successfully written out the code that performs the bulk of the work the calculator should perform. However, at the end of every calculation, we would love to clear the screen. This calculator takes into account that the user may still want to perform an operation with the answer gotten from the previous calculation or would love to begin an entirely different calculation hereby clearing the screen entirely.

To achieve this, the code below does the trick:

if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to exit.\\n").lower() == "y":
            num1 = answer
else:
            repeat = False
            if os.name == 'nt':  # Check if running on Windows
                os.system('cls')  # Clear console screen on Windows
            else:
                os.system('clear')  # Clear console screen on macOS and Linux

calculator()

Considering the code snippet above, each code does the following:

  1. The if-else condition asks the user for input that would either be used to exit the calculator or continue.

  2. If the user chooses the input ythe value of answer becomes the new num1, and the loop continues to the next iteration. If the user chooses to exit by typing n, the loop is terminated by setting repeat to False in the else block.

  3. The code also performs a platform-specific check to clear the screen. If the value of the os.name is nt, this indicates a Windows system, and os.system('cls') is used to clear the screen. Otherwise, for MacOS and Linux systems, it loops into the else condition and uses os.system('clear') to clear the console screen.

  4. Lastly, the calculator function is called to start the calculator.

Final Code

This is an image for the final code of the calculator. If all steps were carried out as stated above, you should have your code like this.

fig 1.0 Viewing the final code for the calculator project

Different Outcomes for Results

This section displays the result of the code when its calculation is successful, when a value error is experienced, and when an invalid choice is entered.

Calculation Successful

Viewing the result after a successful calculation

fig 2.0 Viewing the result after successful calculation

ValueError Experienced

fig 3.0 Viewing the result when a value error is experienced

Invalid Operator entered as Choice

fig 4.0 Viewing the result when an invalid operation is entered as choice

Conclusion

In this article, you have been guided through the step-by-step process to build a calculator with Python. This calculator will enable you to solve several mathematical problems. You should try building yours and feel free to tweak the code to your taste.