Python Program to Make a Simple Calculator

Write a Python program to make a simple calculator that can perform addition, subtraction, multiplication, and division based on the user selected option.

Python Program to Make a Simple Calculator

The below program prints a message about each option and their respective numbers. Here, option 1 = Add, 2 = Subtract, 3 = Multiply, and 4 = Divide. Next, it asks the user to choose the operation they want. Users who enter options 1, 2, 3, and 4 are valid; anything other than those is invalid input.

In the following line of the Python Program, we used two input() statements of integer type to allow users to enter two numbers. Next, the elif statement performs simple calculations based on the user option. Refer to the Python elif statement.

print('''please Select the Operation you  want to Perfom
      1 = Add
      2 = Subtract
      3 = Multiply
      4 = Divide''')
      
opt = int(input("Choose Operation from 1, 2, 3, 4 = "))

n1 = int(input("First Number        = "))
n2 = int(input("Second Number = "))

if opt == 1:
    print(n1, ' + ', n2, '  =  ', n1 +  n2)
elif opt == 2:
    print(n1, ' - ', n2, '  =  ', n1 -  n2)
elif opt == 3:
    print(n1, ' * ', n2, '  =  ', n1 *  n2)
elif opt == 4:
    print(n1, ' / ', n2, '  =  ', n1 /  n2)
else:
    print('Invalid Input')
Python Program to Make a Simple Calculator using elif statement

Simple Calculator using Functions

In this calculator program, we created addition(x, y), subtraction(x, y), multiplication(x, y), and division(x, y) functions to do calculations. Within the print, we are directly calling those Python functions.

def addition(x, y):
    return x + y

def subtraction(x,  y):
    return x - y

def multiplication(x,  y):
    return x * y

def division(x,  y):
    return x / y

opt = int(input("Choose Operation from 1(Add), 2(Sub), 3(Multi), 4(Div) = "))

n1 = int(input("First Number        = "))
n2 = int(input("Second Number = "))

if opt == 1:
    print(n1, ' + ', n2, '  =  ', addition(n1, n2))
elif opt == 2:
    print(n1, ' - ', n2, '  =  ', subtraction(n1, n2))
elif opt == 3:
    print(n1, ' * ', n2, '  =  ', multiplication(n1, n2))
elif opt == 4:
    print(n1, ' / ', n2, '  =  ', divison(n1, n2))
else:
    print('Invalid Input')
Make a Simple Calculator using functions

GUI-based Calculator using Tkinter

Paste the following code to see a modern calculator with a dark theme. It calculates the basic addition, subtraction, multiplication, division, floor divison, exponentiation, and modulus operations.

import tkinter as tk
import ast
import operator
import math

# ---------------- WINDOW ----------------
window = tk.Tk()
window.title("Calculator")
window.geometry("360x560")
window.resizable(False, False)
window.configure(bg="#17191f")

BG = "#17191f"
DISPLAY_BG = "#22252d"
NUM_COLOR = "#30343d"
SPECIAL_COLOR = "#555b66"
OP_COLOR = "#ff9f0a"
TEXT_COLOR = "#ffffff"

expression = ""
just_calculated = False

# ---------------- DISPLAY ----------------
display = tk.Label(
window,
text="0",
bg=DISPLAY_BG,
fg=TEXT_COLOR,
font=("Arial", 30),
anchor="e",
padx=18,
pady=20
)
display.pack(fill="x", padx=14, pady=(16, 12), ipady=12)


# ---------------- SAFE CALCULATION ----------------
def safe_eval(node):
if isinstance(node, ast.Constant):
if type(node.value) in (int, float):
return node.value
raise ValueError("Invalid number")

if isinstance(node, ast.BinOp):
ops = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.FloorDiv: operator.floordiv,
}

fn = ops.get(type(node.op))
if fn is None:
raise ValueError("Invalid operator")

left = safe_eval(node.left)
right = safe_eval(node.right)

# Prevent excessively large exponentiation
if isinstance(node.op, ast.Pow):
if abs(right) > 1000:
raise ValueError("Exponent too large")
if abs(left) > 1e100 and right > 1:
raise ValueError("Result too large")

result = fn(left, right)

if isinstance(result, complex):
raise ValueError("Complex results are not supported")

if isinstance(result, float) and not math.isfinite(result):
raise ValueError("Result too large")

return result

if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.USub):
return -safe_eval(node.operand)
if isinstance(node.op, ast.UAdd):
return safe_eval(node.operand)

raise ValueError("Invalid expression")


def format_result(value):
if isinstance(value, float):
if not math.isfinite(value):
raise ValueError("Invalid result")
if value.is_integer():
return str(int(value))
return str(round(value, 10))

return str(value)


# ---------------- BUTTON ACTIONS ----------------
def press(value):
global expression, just_calculated

if value == "DEL":
expression = expression[:-1]
just_calculated = False
display.config(text=expression or "0")
return

if value == "=":
try:
if not expression:
return

tree = ast.parse(expression, mode="eval")
result = safe_eval(tree.body)
expression = format_result(result)
display.config(text=expression)
just_calculated = True

except (ValueError, SyntaxError, ZeroDivisionError,
OverflowError, TypeError):
expression = ""
display.config(text="Error")
just_calculated = True
return

if just_calculated:
if value in ("+", "-", "*", "/", "//", "**", "%"):
just_calculated = False
else:
expression = ""
just_calculated = False

expression += value
display.config(text=expression)


# ---------------- ROUNDED BUTTON ----------------
def rounded_rectangle(canvas, x1, y1, x2, y2, radius, color):
radius = min(radius, (x2 - x1) / 2, (y2 - y1) / 2)

points = [
x1 + radius, y1,
x2 - radius, y1,
x2, y1,
x2, y1 + radius,
x2, y2 - radius,
x2, y2,
x2 - radius, y2,
x1 + radius, y2,
x1, y2,
x1, y2 - radius,
x1, y1 + radius,
x1, y1,
]

return canvas.create_polygon(
points,
smooth=True,
splinesteps=36,
fill=color,
outline=color
)


def make_button(parent, text, color, command):
width, height = 68, 68

canvas = tk.Canvas(
parent,
width=width,
height=height,
bg=BG,
highlightthickness=0,
bd=0,
cursor="hand2"
)

shape = rounded_rectangle(
canvas, 2, 2, width - 2, height - 2, 17, color
)

label = canvas.create_text(
width / 2,
height / 2,
text=text,
fill=TEXT_COLOR,
font=("Arial", 15, "bold")
)

def on_enter(event):
canvas.itemconfig(
shape, fill="#737985", outline="#737985"
)

def on_leave(event):
canvas.itemconfig(
shape, fill=color, outline=color
)

def on_click(event):
command()

canvas.bind("<Enter>", on_enter)
canvas.bind("<Leave>", on_leave)
canvas.bind("<Button-1>", on_click)
canvas.tag_bind(label, "<Button-1>", on_click)

return canvas


# ---------------- BUTTON LAYOUT ----------------
button_frame = tk.Frame(window, bg=BG)
button_frame.pack(fill="both", expand=True, padx=12, pady=(0, 12))

for row in range(5):
button_frame.grid_rowconfigure(row, weight=1, uniform="row")

for col in range(4):
button_frame.grid_columnconfigure(col, weight=1, uniform="col")

buttons = [
("DEL", SPECIAL_COLOR, "DEL"),
("%", OP_COLOR, "%"),
("**", OP_COLOR, "**"),
("//", OP_COLOR, "//"),

("7", NUM_COLOR, "7"),
("8", NUM_COLOR, "8"),
("9", NUM_COLOR, "9"),
("÷", OP_COLOR, "/"),

("4", NUM_COLOR, "4"),
("5", NUM_COLOR, "5"),
("6", NUM_COLOR, "6"),
("×", OP_COLOR, "*"),

("1", NUM_COLOR, "1"),
("2", NUM_COLOR, "2"),
("3", NUM_COLOR, "3"),
("−", OP_COLOR, "-"),

("0", NUM_COLOR, "0"),
(".", NUM_COLOR, "."),
("+", OP_COLOR, "+"),
("=", OP_COLOR, "="),
]

for index, (label, color, value) in enumerate(buttons):
row = index // 4
col = index % 4

button = make_button(
button_frame,
label,
color,
lambda v=value: press(v)
)

button.grid(
row=row,
column=col,
sticky="nsew",
padx=3,
pady=3
)


# ---------------- KEYBOARD SUPPORT ----------------
def keyboard_input(event):
key = event.keysym
char = event.char

if char in "0123456789.+-%":
press(char)
elif char in "*/":
press(char)
elif char == "-":
press("-")
elif key in ("Return", "KP_Enter"):
press("=")
elif key == "BackSpace":
press("DEL")
elif key == "Escape":
press("DEL")


window.bind("<Key>", keyboard_input)
window.mainloop()

Also Read

  1. Python program to find the Cube of a Number
  2. Python program to find Profit Or Loss