How to Make a Calculator With Python

February 1, 2023

Introduction

A simple calculator in Python is an excellent project for beginners and advanced programmers. The process of making a calculator involves some basic programming concepts. This includes taking user input, conditional statements, and functions.

This guide provides step-by-step instructions to make a calculator with Python.

How to Make a Calculator With Python

Prerequisites

  • Python 3 installed.
  • An IDE or code editor to write the code for the project.
  • A way to run the code (IDE or the command line/terminal).

Step 1: Create a File for the Calculator

The first step covers the following skills:

Start by creating a project directory and a file for the calculator code. On Linux, follow the steps below:

1. Open the terminal (CTRL+Alt+T).

2. Create the project directory with the mkdir command:

mkdir Calculator

3. Change the directory with the following:

cd Calculator

4. Create a file with a .py extension and open it with a text editor, such as nano:

nano calculator.py

Keep the file open and proceed to the next step.

Step 2: Prompt for User Input

The second step covers the following:

The program enables the user to enter two numbers for a simple calculation. Do the following:

1. Fetch a user's input with Python's built-in input() method and save the entry into two variables. Add the following code to the calculator.py file you opened in the previous step:

# Prompt for user input

a = input("Enter the first number: ")
b = input("Enter the second number: ")

The input() method accepts any entry type and saves the entered information as a string.

2. Limit user entry to numbers. If performing calculations with whole numbers (integer calculations), encase the input() method in int() to convert the input into an integer:

# Prompt for user input

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

The better option is to use float() to perform more precise calculations. To allow decimal calculations, convert the user entry into floating point numbers:

# Prompt for user input

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
Python calculator input numbers code

In both cases, the program throws an error if the user enters anything that is not a number.

3. Save the file and close the editor (for nano, use CTRL+X, confirm with Y, and hit Enter).

4. Run the program to see how it works:

python3 calculator.py
Python enter two numbers calculator terminal output

Test multiple times to see the behavior for different user entries.

Note: input() function can also be used to read from stdin in Python. Learn more in our article How to Read From stdin in Python.

Step 3: Perform Operations

The third step covers the following concepts:

Decide what kind of operations the calculator performs. Below is a brief table with the available built-in operators in Python.

OperatorDescription
+Addition
-Subtraction
*Multiplication
**Power (exponent)
/Division
//Floor division
%Modulo (division remainder)

To create and test different operations:

1. Open the calculator.py file again:

nano calculator.py

2. Add the following code to the file to print the result of different operations:

# Prompt for user input

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# Perform operations

print("Sum: {} + {} = {}".format(a,b,a+b))
print("Difference: {} - {} = {}".format(a,b,a-b))
print("Product: {} * {} = {}".format(a,b,a*b))
print("Quotient: {} / {} = {}".format(a,b,a/b))
print("Power: {}^{} = {}".format(a,b,a**b))
print("Division with remainder: {} / {} = {} Remainder: {}".format(a,b,a//b,a%b))
Python calculator operations print code

The program takes the two input numbers and prints the result of different calculations using string concatenation.

3. Save and close the file.

4. Run the program to test:

python3 calculator.py
Python calculator operations print terminal output

Enter any two numbers to see the result of all the operations.

Step 4: Add Conditions

The fourth step covers these functionalities:

  • Multiline printing.
  • Conditional statements.
  • Catching errors with try except blocks.

Conditional statements in Python help control the program flow based on a value. Instead of performing all operations on the two input numbers, allow users to choose and check the input using a conditional statement.

A multiline comment enables a quick way to create a menu with choices.

Change the code in the calculator.py file to match the following:

# First part: Prompt for user input

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

print("""
Choose an operation from the list:
1. Addition
2. Subtraction
3. Multiplication
4. Exponentiation
5. Division
6. Division with remainder
""")

op = int(input("Enter the choice number: "))

# Second part: Perform operations based on input

if op == 1:
        print("Sum: {} + {} = {}".format(a,b,a+b))
elif op == 2:
        print("Difference: {} - {} = {}".format(a,b,a-b))
elif op == 3:
        print("Product: {} * {} = {}".format(a,b,a*b))
elif op == 4:
        print("Power: {}^{} = {}".format(a,b,a**b))
elif op == 5:
        try:
            print("Quotient: {} / {} = {}".format(a,b,a/b))
        except:
            print("Division by 0 not possible!")
elif op == 6:
        try:
            print("Division with remainder: {} / {} = {} Remainder: {}".format(a,b,a//b,a%b))
        except:
            print("Divsion by 0 not possible!")
else:
        print("No such choice!")

The code adds new features and functionalities. Below is a brief overview:

  • The first part of the code generates a simulated user menu with choices (multiline comments). The program saves the user input into variables (first number, second number, and operation).
Python calculator user input and menu code
  • The second part of the code takes the user input variables and performs a calculation based on the input. The final else block prints a message if a user chooses something that's not an option in the program.
  • In the case of division by zero, the program uses a try except block to catch the program error and prints a descriptive error message.
Python calculator division by zero try except code

Save and run the code to see how the program works:

python3 calculator.py
Python calculator with menu terminal output

Run the code several times for different user inputs to see how the output and behavior differ.

Step 5: Create Functions

The fifth step in the calculator program covers the following:

  • Separating code into functions.
  • Looping the program.

Separate the code into logical units and use a recursive function to loop the program. Modify the code in the calculator.py file to match the following:

def prompt_menu():
    a = float(input("Enter the first number: "))
    b = float(input("Enter the second number: "))
    print("""
Choose an operation from the list:
1. Addition
2. Subtraction
3. Multiplication
4. Exponentiation
5. Division
6. Division with remainder
    """)
    op = int(input("Enter the choice number: "))
    return a, b, op

def calculate():
    a, b, op = prompt_menu()
    if op == 1:
        print("Sum: {} + {} = {}".format(a,b,a+b))
    elif op == 2:
        print("Difference: {} - {} = {}".format(a,b,a-b))
    elif op == 3:
        print("Product: {} * {} = {}".format(a,b,a*b))
    elif op == 4:
        print("Power: {}^{} = {}".format(a,b,a**b))
    elif op == 5:
        try:
            print("Quotient: {} / {} = {}".format(a,b,a/b))
        except:
            print("Division by 0 not possible!")
    elif op == 6:
        try:
            print("Division with remainder: {} / {} = {} Remainder: {}".format(a,b,a//b,a%b))
        except:
            print("Divsion by 0 not possible!")
    else:
        print("No such choice!")
    loop()

def loop():
    choice = input("Do you want to continue? (Y,N): ")
    if choice.upper() == "Y":
        calculate()
    elif choice.upper() == "N":
        print("Goodbye!")
    else:
        print("Invalid input!")
        loop()

calculate()

The code has three distinct functions:

  • The prompt_menu() function contains the user menu and returns the two input numbers and selected operation.
  • The calculate() function uses the prompt_menu() function to gather the user input and calculate based on the provided information.
  • The loop() function creates a loop menu where the user chooses whether to continue using the program. In case of invalid input, the function recursively calls itself and reruns the function. The final line in the calculate() function calls the loop() function.
Python recursive function loop code

After the function definitions, the program calls the calculate() function to run the program loop.

Save the code and run the program with the following:

python3 calculator.py
Python calculator loop terminal output

The program loops until the user enters N or n to exit the program.

Conclusion

After working through the steps in this guide, you have a fully-functional calculator program written in Python. Improving the existing code or taking a completely different approach is possible.

Once ready, use Git to store and manage your project.

Was this article helpful?
YesNo
Milica Dancuk
Milica Dancuk is a technical writer at phoenixNAP who is passionate about programming. Her background in Electrical Engineering and Computing combined with her teaching experience give her the ability to easily explain complex technical concepts through her content.
Next you should read
Linux bc Command with Examples
January 12, 2023

The bc command is a command-line utility in Linux allowing users to perform complex mathematical and arithmetic...
Read more
Bash Math Operations (Bash Arithmetic) Explained
April 14, 2022

You can perform math and arithmetic operations in Bash directly. Although...
Read more
How to Install NumPy
May 8, 2020

NumPy (Numerical Python) is an open-source library for the Python programming language. It is used for scientific computing and...
Read more
Python SciPy Tutorial - A Guide for Beginners
February 25, 2021

When NumPy is not enough, SciPy has you covered. SciPy is a Python library used for scientific computing. It...
Read more