Python Simple Calculator Program

Short answer
A simple Python calculator reads two numbers and an operator with input(), then uses if/elif (or a dictionary of functions) to apply +, -, * or /, checking for division by zero.

A calculator is a perfect beginner project because every step is small: take input, convert text to numbers, choose an operation, print a result. Along the way you practise functions, if/else decisions and basic error handling.

This page builds a calculator that handles one calculation at a time, then shows cleaner ways to organise it. A larger version with a menu and a loop is covered in the calculator project lesson.

Quick facts
InputTwo numbers and one operator (+, -, *, /)
OutputThe result of the calculation, or an error message
ApproachConvert input to float, choose the operation with if/elif, guard division by zero
Time complexityO(1)

Approach: how to build a calculator in Python step by step

  1. Ask for the first number and convert it with float().
  2. Ask for the operator as text.
  3. Ask for the second number and convert it too.
  4. Compare the operator with +, -, * and / using if/elif.
  5. For /, check that the second number is not zero first.
  6. Print the result, or a message for an unknown operator.

Put the decision logic in a function such as calculate(a, op, b) that returns the result instead of printing it. Then the function is easy to test and reuse, and only the outer code deals with input() and print().

How the calculator code works

input() always returns a string, so float(input(...)) is needed before doing arithmetic (see input and output). The function checks the operator with several if statements; each return ends the function, so no else is required. Division is the only operation that can fail, so it gets its own guard, which avoids a ZeroDivisionError.

Python
print(10 / 4)
print(10 // 4)
print(10 % 4)
print(2 ** 5)

Variations: dictionary of operators and match statement

With many operators, a long if/elif chain gets noisy. A dictionary that maps each symbol to a function from the operator module keeps the code short, and adding % or ** is a one-line change. Python 3.10+ also offers match/case; see the match statement lesson. All three styles give the same results, so choose the one you find easiest to read.

Common calculator operators

Arithmetic operators you can add to the calculator
SymbolOperationExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/True division7 / 23.5
//Floor division7 // 23
%Remainder7 % 21
**Power7 ** 249

Examples you can run

Press Run, then edit the code and run it again.

Calculator function with safe division

The function returns a result or a message, so the calling code stays tiny.

Calculator function with safe division
def calculate(a, op, b):
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    return "Unknown operator"

print(calculate(12, "*", 4))
print(calculate(7, "/", 2))
print(calculate(5, "/", 0))
print(calculate(5, "^", 2))
Expected output48
3.5
Cannot divide by zero
Unknown operator

Interactive calculator with input()

The program reads two numbers and an operator. The values 12, * and 4 are typed by the user.

Interactive calculator with input()
def calculate(a, op, b):
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    return "Unknown operator"

a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
print("Result:", calculate(a, op, b))
Expected outputFirst number: 12
Operator (+, -, *, /): *
Second number: 4
Result: 48.0

Alternative: dictionary of operator functions

Each symbol maps to a function from the operator module. Using .get() handles unknown symbols without a long if chain.

Alternative: dictionary of operator functions
import operator

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

def calculate(a, op, b):
    func = OPS.get(op)
    if func is None:
        return "Unknown operator"
    try:
        return func(a, b)
    except ZeroDivisionError:
        return "Cannot divide by zero"

print(calculate(20, "-", 5))
print(calculate(9, "/", 3))
print(calculate(1, "/", 0))
print(calculate(1, "%", 2))
Expected output15
3.0
Cannot divide by zero
Unknown operator

Edge case: division by zero in the interactive version

The guard in calculate() prevents a crash and the user sees a friendly message.

Edge case: division by zero in the interactive version
def calculate(a, op, b):
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    return "Unknown operator"

a = float(input("First number: "))
op = input("Operator: ")
b = float(input("Second number: "))
print("Result:", calculate(a, op, b))
Expected outputFirst number: 8
Operator: /
Second number: 0
Result: Cannot divide by zero

Common mistakes

Adding numbers that are still strings

✗ Wrong

a = input("First: ")
b = input("Second: ")
print(a + b)
No error, but typing 2 and 3 prints 23, because `+` joins two strings.

✓ Right

a = float("2")
b = float("3")
print(a + b)

Convert with int() or float() before the calculation.

Dividing without checking for zero

✗ Wrong

a = 10
b = 0
print(a / b)
ZeroDivisionError: division by zero

✓ Right

a = 10
b = 0
if b == 0:
    print("Cannot divide by zero")
else:
    print(a / b)

Check if b == 0 first, or catch ZeroDivisionError with try/except.

Python Simple Calculator Program: questions people ask

How do I make a simple calculator in Python?

Read two numbers with float(input()), read an operator, then use if/elif to perform +, -, * or / and print the result. Guard division so that dividing by zero does not crash the program.

Why does my Python calculator print 23 instead of 5 for 2 + 3?

Because input() returns strings and + concatenates strings. Wrap each input in int() or float() first.

How can I let the calculator run more than one calculation?

Put the input and calculation code inside a while True: loop and break when the user types a quit command such as q.

Keep learning

Step-by-step lessons:
Python FunctionsPython if, elif and elsePython Calculator Project

Related:
Python BMI Calculator ProgramPython Tip Calculator Program (Split the Bill)Python input() FunctionPython Number Guessing Game Program

More in mini programs:
Python Number Guessing Game ProgramPython Random Password Generator ProgramPython BMI Calculator ProgramPython Rock Paper Scissors Game ProgramPython Tip Calculator Program (Split the Bill)Python Star Pattern Programs (Triangle, Pyramid, Diamond) See all →