Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a calculator in Python

Introduction

In this tutorial, we will create a simple calculator application in Python. This calculator will be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. We will be using Python, a high-level, easy-to-learn programming language that is widely used in various domains.

This tutorial is intended for beginners who are learning programming, so we will avoid using jargons as much as possible, and if we use any, we will explain them in simple terms. We will also provide actual code examples and give intuitions and analogies to help you understand the concepts better.

Getting Started

Before we start writing the calculator code, make sure you have Python installed on your computer. If you don't have Python installed, you can download it from the official Python website.

Once Python is installed, open your favorite text editor or integrated development environment (IDE) to write and run Python code. Some popular choices are Visual Studio Code, PyCharm, or the built-in Python IDE, IDLE.

Defining Calculator Functions

First, let's define four functions that will perform the basic arithmetic operations:

  1. Addition
  2. Subtraction
  3. Multiplication
  4. Division

Addition

The addition function will take two numbers as input and return their sum. In Python, we can define a function using the def keyword followed by the function name and the list of input parameters enclosed in parentheses.

Here's the code for the addition function:

def add(a, b):
    return a + b

In this code, we define a function called add that takes two input parameters, a and b. The function returns the sum of a and b using the + operator.

Subtraction

The subtraction function will take two numbers as input and return the difference between them.

Here's the code for the subtraction function:

def subtract(a, b):
    return a - b

In this code, we define a function called subtract that takes two input parameters, a and b. The function returns the difference between a and b using the - operator.

Multiplication

The multiplication function will take two numbers as input and return their product.

Here's the code for the multiplication function:

def multiply(a, b):
    return a * b

In this code, we define a function called multiply that takes two input parameters, a and b. The function returns the product of a and b using the * operator.

Division

The division function will take two numbers as input and return their quotient.

Here's the code for the division function:

def divide(a, b):
    if b == 0:
        return "Cannot divide by zero!"
    return a / b

In this code, we define a function called divide that takes two input parameters, a and b. Before performing the division, we check if b is equal to zero using the == operator. If b is zero, we return an error message "Cannot divide by zero!" to handle the division by zero case. If b is not zero, the function returns the quotient of a and b using the / operator.

User Interface

With the four basic arithmetic functions defined, let's now create a simple user interface (UI) that allows users to input two numbers and select an operation to perform.

Getting User Inputs

To get user inputs, we will use the input() function, which reads a line of text from the user and returns it as a string. To convert the string to a number, we can use the float() function, which takes a string as input and returns a floating-point number.

Here's the code to get user inputs for two numbers:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

Choosing an Operation

Next, let's ask the user to choose an operation to perform. We will display a menu of available operations and use the input() function to get the user's choice.

Here's the code to display the menu and get the user's choice:

print("Choose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

operation = input("Enter the operation number (1/2/3/4): ")

Performing the Operation

Now that we have the two numbers and the user's choice of operation, we can use an if statement to call the appropriate function and display the result.

Here's the code to perform the chosen operation and display the result:

if operation == "1":
    print("The result of the addition is:", add(num1, num2))
elif operation == "2":
    print("The result of the subtraction is:", subtract(num1, num2))
elif operation == "3":
    print("The result of the multiplication is:", multiply(num1, num2))
elif operation == "4":
    print("The result of the division is:", divide(num1, num2))
else:
    print("Invalid operation number! Please try again.")

In this code, we use an if statement to check the value of the operation variable. If the value is "1", we call the add() function and display the result. If the value is "2", we call the subtract() function and display the result, and so on. If the value is not one of the valid operation numbers, we display an error message.

Complete Calculator Code

Here's the complete code for our calculator application:

# Calculator functions
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Cannot divide by zero!"
    return a / b

# Getting user inputs
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Choosing an operation
print("Choose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

operation = input("Enter the operation number (1/2/3/4): ")

# Performing the operation and displaying the result
if operation == "1":
    print("The result of the addition is:", add(num1, num2))
elif operation == "2":
    print("The result of the subtraction is:", subtract(num1, num2))
elif operation == "3":
    print("The result of the multiplication is:", multiply(num1, num2))
elif operation == "4":
    print("The result of the division is:", divide(num1, num2))
else:
    print("Invalid operation number! Please try again.")

Conclusion

Congratulations! You've just created a simple calculator application in Python that can perform basic arithmetic operations. As you progress in your programming journey, you can enhance this calculator by adding more features, such as more advanced mathematical operations, error handling, or a graphical user interface (GUI) using libraries like Tkinter or PyQt.

We hope this tutorial has helped you understand the basics of Python and how to create a simple application from scratch. Keep learning and experimenting, and most importantly, have fun programming!