Python programs / Numbers / Simple calculator

Python Program to Make a Simple Calculator

Beginner Numbers

A calculator function that adds, subtracts, multiplies or divides two numbers, with a message instead of an error for division by zero.

A calculator is a classic first program with if statements: it takes two numbers and an operator, such as *, and works out the answer. Here it's a function, so calculate(7, "*", 6) returns 42. Its one catch is division by zero, which has no answer: Python would stop the program with a ZeroDivisionError, so the function checks for it first and returns a message instead.

Program

def calculate(a, operator, b):
    """The result of a operator b, for + - * and /."""
    if operator == "+":
        return a + b
    elif operator == "-":
        return a - b
    elif operator == "*":
        return a * b
    elif operator == "/":
        if b == 0:
            return "Can't divide by zero"
        return a / b
    else:
        return "Unknown operator: " + operator


print("7 * 6:", calculate(7, "*", 6))
print("7 / 2:", calculate(7, "/", 2))
print("7 / 0:", calculate(7, "/", 0))

Open in the editor Download calculator.py

Output

7 * 6: 42
7 / 2: 3.5
7 / 0: Can't divide by zero

How it works

  1. The function compares operator with each sign in turn, from the top, and returns the answer for the first one that matches. return ends the function, so the checks after the match never run.
  2. Division needs one more check first. Dividing by zero would stop the program with an error, so when b is 0 the function returns a message instead. Otherwise it divides.
  3. Any other sign, such as %, gets a message too. Without the else, the function would end without a return and give back None.
  4. The program multiplies, divides, and tries to divide by zero. / always gives a float, so 7 / 2 is 3.5.

Other ways to write it

With try and except

Instead of checking b first, the function can try the division and catch the error Python raises (errors and exceptions):

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Can't divide by zero"

print(divide(7, 2), divide(7, 0))

With a dictionary of operators

The operator module has a function for each sign, and a dictionary can match each sign to its function. A new sign is then one more entry, not another elif. The argument is called sign here so it doesn't hide the module's name, and an unknown sign raises a KeyError.

import operator

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

def calculate(a, sign, b):
    if sign == "/" and b == 0:
        return "Can't divide by zero"
    return OPERATIONS[sign](a, b)

print(calculate(7, "+", 6), calculate(7, "-", 6))

Try it yourself

  • Try the other signs, as calculate(7, "+", 6) and calculate(7, "-", 10).
  • Divide 8 by 2: the answer is 4.0, not 4, because / always gives a float. Add // for whole-number division.
  • Add % for the remainder and ** for powers.
  • Pass a sign the function doesn't know, such as "^", to see the message.

More numbers programs

Share this program