In this tutorial, we’ll learn to create a simple command-line based calculator which will add, subtract, multiply, and divide. Python is one of the best programming languages for beginners in programming. Due to its simple and easy-to-understand syntax, it eliminates a lot of language-related barriers and allows programmers to focus on the core logic of a program.

Following is a step-by-step tutorial towards building a simple calculator program in Python.

Contents

## Overview of Our Calculator Program

We will build a command-line based calculator program which will continuously take input from the user. It is a simple program that asks the user to select from a pool of options to perform basic arithmetic operations of addition, subtraction, multiplication, and division. At any point in time, the user will have the option to exit from the program.

We will frequently use functions throughout this program. If you’re not familiar with functions in Python, make sure to give a read to our detailed tutorial here. Without further ado, let’s get started!

## Setting Up the Project

Navigate to the directory in which you wish to create the project. Create a file called calculator.py in the project directory.

Once you create the required file, open the file in any IDE you like. I will be using PyCharm throughout this project and I recommend the same to you.

Create a function called calculator() in the file and leave it as is for now by writing pass in it. We will build this function gradually as we progress in this tutorial.

def calculator():
'''
This is our main function which entails the flow of our calculator program
'''
pass

## Creating the Program Entry Point

The following piece of code helps Python to start the execution of the program. It creates an entry point for the program and defines a sequence of steps in which the program executes. In our case, we will use this entry point as follows.

# Program's Entry Point
if __name__ == "__main__":
calculator()

Our first task is to create a menu of options that will guide the user to select an option in our program. Let’s create a function to display the menu.

def displayMenu():
print("----------------------------")
print("Enter (-) for Subtraction")
print("Enter (*) for Multiplication")
print("Enter (/) for Division")
print("Enter (e) to Exit")
print("----------------------------")

The above function displays a list of choices to the user. The user can enter any choice from the list of options. Note that we will bind the user to select from the given options. If the user enters some invalid option, we will display an error message.

## Enabling the Program to Run Continuously

We discussed in the introduction that at any point in time we will allow the user to exit from the program which means that we first need to enable the program to run continuously until the user asks to exit. We will achieve this functionality with an infinite while loop as follows.

while True:
pass

All of our coding and implementation will fall under this while loop because we want the program and its entities to run continuously.

## Taking the User Input and Program Execution

We will take three inputs from the user. The first input will allow the user to select from the list of menu options. The other two inputs will be for the user to enter numerical data to perform the selected operation. We can take the user input and proceed with the program as follows.

validMenuOptions = ["+", "-", "*", "/", "e"]
while True:

print("[-] Error: Invalid Input!")
print("[+] Program Terminated!")
break
else:
# Asking user to enter numbers
try:
firstNumber = float(input("Enter 1st Number: "))
secondNumber = float(input("Enter 2nd Number: "))

result = 0

# Checking each possibility and storing the output in 'result' variable
result = firstNumber + secondNumber
result = firstNumber - secondNumber
result = firstNumber * secondNumber
if secondNumber == 0:
print("[-] Error: Cannot divide by zero")
else:
result = firstNumber / secondNumber
except:
print("[-] Error: Invalid Input! Only numerical input is allowed.")

All lost? There is a lot going on in the above code snippet. Don’t worry we will break it down step-by-step and understand each line of code separately in the next section.

### Understanding the Program Flow

At line 1 we are just maintaining a list of valid menu options which our program supports. We are doing this so that when the user enters the input, we can check if the user entered something which belongs to the list of our supported options. At line 2, we are creating an infinite while loop for the continuous execution of the program. After that, we are showing a menu list to the user to select the supported option. Once the user sees the menu list, we are asking input from the user to select an option from the menu.

At line 8 and 9, we are checking for the input validity and displaying an error message accordingly. We exit from the code if the user chooses to exit (e) in the next three lines of code.

Once all the validation is done, we allow the user to enter the numbers so that our program can execute the selected operation on these numbers. Since we expect a numeric input from the user, upon typecasting, there should be an error if the user enters a non-numeric input. From line 15 to 38, we have a try-except block so that we immediately catch that exception and display the error message accordingly. If there is no error, the program seamlessly runs from line 16 to 36

### Executing the Program

By now, we have coded a simple Python application that works as a command-line based calculator. Save your file. Run the following command in the project directory and start using your calculator app.

python calculator.py

You can access the source code of this calculator app here.

If you wish to learn more about Python, you can check out our collection of Python tutorials.