# How to Make a Calculator With Python {in 5 Steps} – phoenixNAP

Create a calculator in python

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 for making a calculator with Python.

• Prerequisites Python 3 installed
• . An IDE or code editor to write the project code.

• A way to execute the code (IDE or command line/terminal).

## Step 1: Create a file for the calculator

The first step covers the following skills:

Creation

• of directories. Creation of
• files.

• Edit files in a text editor.

Start by creating a project directory and 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 command mkdir: 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: Request

user input

The second step covers the following:

• . Take user input.

• Convert user input to a desired data type
• .

• Save and run the code
• .

• The

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

1. Get input from a user with Python’s built-in input() method and save the input in two variables. Add the following code to the calculator.py file that you opened in the previous step

: # Prompt user input a = input(“Enter the first number://”) b = input(“Enter the second number://”)

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

2. Limit user input to numbers. If you perform calculations with integers (integer calculations), include the input() method in int() to convert the input to an integer: # Request user input a = int(input(“Enter the first number: “)) b = int(input(“Enter the second number: “))

The best option is to use float() to perform more accurate calculations. To allow decimal calculations, convert user input to floating-point numbers

: # Request user input a = float(input(“Enter the first number: “)) b = float(input(“Enter the second number: “))

In both cases, the program throws an error if the user enters something other than a number.

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

4. Run the program to see

how it works

: python3 calculator.py

Test several times to see the behavior of different user input

.

## Step 3: Perform

operations

The third step covers the following concepts:

• Mathematical operators
• . Attachment of strings. Decide what kind of operations the calculator

• performs.

Below is a brief table with the built-in operators available in Python.

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 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: {} / {} = {} Rest: {}”.format(a,b,a//b,a%b))

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

Enter any two numbers to see the result of all operations

.

The fourth step covers these functionalities:

• Multi-line printing
• . Conditional

• statements. Error detection with try except blocks
• .

• Conditional

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

A multi-line comment allows you to create a menu with options.

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

: # Part One: Prompt user input a = float(input(“Enter first number: “)) b = float(input(“Enter second number: “)) print(“”” Choose an operation from the list: 1. Addition 2. Subtract 3. Multiplication 4. Exponentiation 5. Division 6. Division with the rest “””) op = int(input(“Enter the choice number: “)) # Second part: Perform operations based on the 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 is not possible!”) elif op == 6: try: print(“Division with remainder: {} / {} = {} Rest: {}”.format(a,b,a//b,a%b)) except: print(“Divsion by 0 is not possible!”) else: print(“There is no such choice!”)

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

• The first part of the code generates a simulated user menu with options (multi-line comments). The program saves user input in variables (first number, second number, and operation).
• The second part of the code takes the input variables from the user and performs a calculation based on the input. The last else block prints a message if a user chooses something that is not an option in the program.
• In the case of division by zero, the program uses a try except block to detect the program error and prints a descriptive error message.

Save and run

the code to see how the program works: python3 calculator.py Run the code

multiple times for different user input to see how the output and behavior differ

.

## Step 5: Create

functions

The fifth step in the calculator program covers the following:

Separate code into

functions.

• Program loop
• .

• Separate the code into

logical units and use a recursive function to play 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. Subtract 3. Multiplication 4. Exponentiation 5. Division 6. Division with rest “””) 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 is not possible!”) elif op == 6: try: print(“Division with remainder: {} / {} = {} Rest: {}”.format(a,b,a//b,a%b)) except: print(“Divsion by 0 is not possible!”) else: print(“There is 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 the selected operation. The calculate() function uses the prompt_menu() function

• to collect user input and calculate based on the information provided. The loop
• (
• ) function It 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 reexecutes the function. The last line of the calculate() function calls the loop() function.

After the function

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

Save the code and run the program with the following:

python3 calculator.py

The program repeats until the user enters N or n to exit the program

.

Conclusion

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

Once you’re done, use Git to store and manage your project.