How to Make a Simple Calculator in Python


1. Instruction

In this example we will show how to create a simple calculator in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Define functions for addition, subtraction, multiplication, and division

# Add two numbers
def add(x, y):
    return x + y

# Subtraction of two numbers
def subtract(x, y):
    return x - y

# Multiply two numbers
def multiply(x, y):
  return x * y

# Dividing two numbers
def divide(x, y):
    return x / y


# Select the action to be taken
print("Available Options:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter your choice: ")

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

if choice == '1':
    print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':
    print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':
    print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':
    print(num1, "/", num2, "=", divide(num1, num2))
else:
    print("Illegal input")

We can obtain the results  as follows:

Available Options:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice: 4
Enter the first number: 5
Enter the second number: 4
5 / 4 = 1.25
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments