Editor

Python Program to Make a Simple Calculator

Beginner · Basics

A simple calculator takes two numbers and an operator (+, -, * or /) and prints the result. This program puts the calculation in a function and handles the two things that can go wrong: dividing by zero and an operator it does not know.

Program

simple_calculator.py
def calculate(a, operator, b):
if operator == "+":
return a + b
elif operator == "-":
return a - b
elif operator == "*":
return a * b
elif operator == "/":
if b == 0:
return "Error: cannot divide by zero"
return a / b
else:
return "Error: unknown operator " + operator
# With input() you would ask for each part:
# a = float(input("First number: "))
# operator = input("Operator (+, -, *, /): ")
# b = float(input("Second number: "))
print("12 + 4 =", calculate(12, "+", 4))
print("12 - 4 =", calculate(12, "-", 4))
print("12 * 4 =", calculate(12, "*", 4))
print("12 / 4 =", calculate(12, "/", 4))
print("12 / 0 =", calculate(12, "/", 0))
print("12 ^ 4 =", calculate(12, "^", 4))
Output
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3.0
12 / 0 = Error: cannot divide by zero
12 ^ 4 = Error: unknown operator ^

How it works

  1. calculate() compares operator with each symbol in turn and returns the matching result.
  2. Division checks b == 0 first, because dividing by zero would stop the program with a ZeroDivisionError.
  3. An operator that matches none of the four, like ^, falls through to the else branch and returns an error message.
  4. The / operator always gives a decimal result in Python 3, which is why 12 / 4 prints 3.0.

Another way to write it

Using match-case (Python 3.10 and later)

Using match-case (Python 3.10 and later)
def calculate(a, operator, b):
match operator:
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b if b != 0 else "Error: cannot divide by zero"
case _:
return "Error: unknown operator " + operator
print("7 * 6 =", calculate(7, "*", 6))
print("9 / 0 =", calculate(9, "/", 0))
print("2 % 5 =", calculate(2, "%", 5))
Output
7 * 6 = 42
9 / 0 = Error: cannot divide by zero
2 % 5 = Error: unknown operator %

match compares the operator with each case in turn, and case _ catches everything else. It reads like a menu, but it needs Python 3.10 or newer.

Try it yourself

Add % for the remainder and ** for the power to the calculator, then test both.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises