Skip to content
Devtoolry

Patterns and small projects · intermediate

Python Program to Make a Simple Calculator

Build a simple calculator in Python that reads expressions like "12 * 4", picks the operation from a dictionary and handles division by zero and bad input.

A calculator is a small but complete program: it reads input, validates it, chooses an operation and reports errors instead of crashing. Instead of a long if/elif chain, this version stores the operations in a dictionary that maps each symbol to a function.

The program

Python
import operator
import sys

OPERATIONS = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
}

def calculate(line):
    try:
        left, symbol, right = line.split()
        return OPERATIONS[symbol](float(left), float(right))
    except ValueError:
        return "Error: write it as: number operator number"
    except KeyError:
        return f"Error: unknown operator {symbol}"
    except ZeroDivisionError:
        return "Error: cannot divide by zero"

for line in sys.stdin:
    if line.strip():
        print(line.strip(), "->", calculate(line))
Input (stdin)
12 * 4
7 / 2
5 / 0
3 ^ 2
hello
Output
12 * 4 -> 48.0
7 / 2 -> 3.5
5 / 0 -> Error: cannot divide by zero
3 ^ 2 -> Error: unknown operator ^
hello -> Error: write it as: number operator number

How it works

  1. OPERATIONS maps each symbol to a function from the operator module, so operator.mul(12, 4) is 12 * 4.
  2. line.split() splits "12 * 4" into three parts; a line with a different number of parts raises ValueError when unpacked into three names.
  3. OPERATIONS[symbol] looks up the function and calls it with the two numbers converted to float.
  4. Each kind of failure has its own except block with a helpful message, so one bad line does not stop the program.
  5. for line in sys.stdin reads every line of input, which lets you test many calculations in one run.

Watch it run line by line

Visualize the program and follow the line "5 / 0": the call to calculate raises ZeroDivisionError, and the highlighted line jumps to the matching except block, where the return row shows the message.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: The classic if/elif version

An if/elif chain is easier to read when you are starting out. The dictionary version scales better: adding an operator such as % or ** is one new line.

Python
a, op, b = 10, "-", 4
if op == "+":
    print(a + b)
elif op == "-":
    print(a - b)
elif op == "*":
    print(a * b)
elif op == "/":
    print(a / b if b != 0 else "cannot divide by zero")
else:
    print("unknown operator")
Output
6

Common mistakes

  • Using eval() on the input: it runs any Python code the user types. Parse the input yourself, as here.
  • Catching every error with a bare except:, which also hides bugs in your own code.
  • Converting with int() instead of float(), so decimal input such as "2.5 + 1" raises ValueError.

Try it yourself

  • Add % (remainder) and ** (power) to the dictionary.
  • Allow expressions without spaces, such as "12*4", by finding the operator in the string.
  • Keep a running total so the next line can start with an operator: "+ 5".

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.