Thuta Learning
Python
ProjectsProgrammingBeginner

Calculator App (Enhanced)

PythonLesson 6440 min

What you'll walk away with

  • Explain why running a user's expression with eval() is dangerous
  • Build a dict that maps operator symbols to functions (an allowlist)
  • Represent user-fixable problems with a custom exception such as CalculatorError
  • Pass read and write functions in, so the interactive loop can be tested without a keyboard

Explain it simply

Explain it simply

Like a restaurant that separates the waiter from the kitchen, this calculator is split into two parts. The waiter (the interface) takes the customer's order, asks again when it is unclear and serves the result. The kitchen (the logic) reads only the order slip and cooks; it never talks to the customer.

With this split you can test the kitchen without any customer: hand it the slip "10 / 0" and check that it refuses properly. And if the waiter later changes from a terminal to a GUI or a web page, the kitchen stays untouched.

Problem → Why → Solution

The problem: the one-line eval() calculator

The shortest possible calculator is print(eval(input("> "))). Type "5 + 3" and you get 8, which feels like magic at first. But eval() runs any Python code at all. If a user types __import__('os').remove('data.db') the file is deleted, and putting this calculator behind a web form hands strangers remote control of the server.

A plain calculator that avoids eval() can still have two other problems. If input() and print() are mixed into the calculation code, nothing can be tested. And if divide() returns the string "Error! Division by zero." on failure, a caller that treats the result as a number and keeps calculating hits a TypeError.

calc_danger.py
print(eval(input("> ")))     # "5 + 3" -> 8 ... and also any Python code

def divide(a, b):
    if b == 0:
        return "Error! Division by zero."   # a str where a number was expected
    return a / b

total = divide(10, 0) + 1    # TypeError: can only concatenate str (not "int") to str

Why does this happen?

eval() does not see the input as an arithmetic expression; it sees a complete Python program. Without an allowlist of what is permitted, the user can run anything. Returning an error as a string mixes success and failure into one return type, whereas raising an exception is something a caller cannot silently ignore.

Core concept: split the logic from the interface

The real lesson of this project is not arithmetic but layering. The logic layer takes a string and returns a result or raises an exception. The interface layer reads a line from the user, calls the logic and shows either the result or an error message. Each piece has one job.

text
Two layers of the calculator
----------------------------
  user types "15 / 4"
         |
+--------v--------------------- interface (run_session) ---+
| read(prompt) -> line ; 'q' / 'help' handled here          |
| try: write("= " + evaluate_line(line))                    |
| except CalculatorError: write("Error: ...")               |
+--------|--------------------------------------------------+
         v
+------------------------------- logic (pure functions) ----+
| evaluate_line -> split into 3 parts                       |
| parse_number  -> float or CalculatorError                 |
| calculate     -> OPERATIONS[op](a, b) or CalculatorError  |
+-----------------------------------------------------------+

1. An operator allowlist

The OPERATIONS dict maps "+" to operator.add and "/" to operator.truediv. Any symbol not in the dict is rejected, so the user can never do more than you allowed. Adding an operator is one new line in the dict instead of another elif branch.

2. One exception type for user-fixable errors

Not a number, unknown operator, division by zero, wrong format: each raises CalculatorError. The interface catches that one type and shows its message. Programming bugs such as NameError are not caught, so they are never hidden.

3. Inject input and output as parameters

run_session(read, write) never calls input() or print() directly. The real program calls run_session(read=input, write=print); a test passes a function that replays prepared lines. This is dependency injection, and it lets you check the loop's q, help and error paths without a keyboard.

4. Session commands belong to the interface

"q" and "help" control the session rather than compute anything, so run_session() handles them. The logic never knows these commands exist, which means a web version can replace "q" with closing the tab and help with a tooltip.

User typesHandled byOutcome
15 / 4Logic= 3.75
10 / 0Logic (CalculatorError)Error message, session continues
abc * 2Logic (parse_number)Error message, session continues
helpInterfaceLists the operators
qInterfacePrints Bye! and ends the loop

The number type was chosen deliberately too. float accepts decimals like 2.5 and negatives like -7, which is enough for an everyday calculator. For a money calculator you would switch parse_number() from float to Decimal, and nothing else in the code would need to change.

Mental model: waiter and kitchen
  1. Interface reads one line
  2. Logic parses and checks allowlist
  3. Result or CalculatorError
  4. Interface shows it, asks again

If you spot input() or print() inside a logic function, the two layers have leaked into each other.

General pattern

python
HANDLERS = {"symbol": function_for_symbol}
class AppError(Exception): ...

def evaluate(text: str) -> Result:       # pure: raise AppError on bad text
    ...

def run(read, write) -> None:            # interface: loop until quit
    while (line := read("> ")) != "q":
        try:
            write(format_result(evaluate(line)))
        except AppError as error:
            write(f"Error: {error}")

A dispatch table, a custom exception, a pure evaluate() and a loop that receives read and write: these four pieces fit most small command-line tools.

Example: the full calculator with a scripted session

This code provides add, subtract, multiply and divide, organised into two layers. In the demo, scripted() replaces the keyboard, handing over one line at a time and echoing it the way a terminal would, so every run prints the same thing. For real use, pass read=input as the last comment shows.

calculator.py
import operator

# ===== 1. Pure logic: no input(), no print() =====
OPERATIONS = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
}


class CalculatorError(Exception):
    """A problem the user can fix by typing something else."""


def parse_number(text: str) -> float:
    try:
        return float(text)
    except ValueError:
        raise CalculatorError(f"'{text}' is not a number") from None


def calculate(a: float, op: str, b: float) -> float:
    if op not in OPERATIONS:
        raise CalculatorError(f"unknown operator '{op}'")
    if op == "/" and b == 0:
        raise CalculatorError("cannot divide by zero")
    return OPERATIONS[op](a, b)


def evaluate_line(line: str) -> str:
    parts = line.split()
    if len(parts) != 3:
        raise CalculatorError("type: number operator number, e.g. 6 * 7")
    a, op, b = parts
    return f"{calculate(parse_number(a), op, parse_number(b)):g}"


# ===== 2. Interface: talks to the user through read/write =====
def run_session(read, write) -> None:
    write("Calculator ready. Type 'help' or 'q'.")
    while True:
        line = read("> ").strip()
        if line in ("q", "quit"):
            write("Bye!")
            return
        if line == "help":
            write("Operators: " + " ".join(OPERATIONS) + "   Example: 6 * 7")
            continue
        try:
            write(f"= {evaluate_line(line)}")
        except CalculatorError as error:
            write(f"Error: {error}")


# ===== 3. Demo: a scripted user instead of the keyboard =====
def scripted(lines):
    remaining = iter(lines)

    def read(prompt: str) -> str:
        line = next(remaining)
        print(prompt + line)          # echo, as a terminal would show it
        return line

    return read


demo = ["5 + 3", "15 / 4", "10 / 0", "2 ^ 3", "abc * 2", "7 -", "help", "q"]
run_session(read=scripted(demo), write=print)
# Real program: run_session(read=input, write=print)

Code breakdown

  1. Allowlist dispatch return OPERATIONS[op](a, b)

    It looks up the function in the dict and calls it immediately. The op not in OPERATIONS check runs first, so a symbol like "^" never gets this far.

  2. Translate the low-level error raise CalculatorError(f"'{text}' is not a number") from None

    float()'s ValueError becomes a CalculatorError with a readable message. from None stops the original ValueError from being chained into the traceback.

  3. Refuse before dividing if op == "/" and b == 0:

    Rather than waiting for Python's ZeroDivisionError, it checks first and raises with a clear message. Because it never returns an error string, calculate() always returns a float.

  4. Compact number formatting return f"{calculate(parse_number(a), op, parse_number(b)):g}"

    The :g format shows 8.0 as 8 and 3.75 as 3.75. It keeps six significant digits, so 1 / 3 shows as 0.333333; change the format if you need more precision.

  5. One except for user errors except CalculatorError as error:

    Every error the logic raises is caught in this one place and the session carries on, which is why the calculator keeps asking for lines even after "10 / 0".

  6. Injected I/Orun_session(read=scripted(demo), write=print)

    The demo list is injected as the keyboard. Swap write=print for a list's append method and a test can check the output as a list, too.

You should see
Calculator ready. Type 'help' or 'q'.
> 5 + 3
= 8
> 15 / 4
= 3.75
> 10 / 0
Error: cannot divide by zero
> 2 ^ 3
Error: unknown operator '^'
> abc * 2
Error: 'abc' is not a number
> 7 -
Error: type: number operator number, e.g. 6 * 7
> help
Operators: + - * /   Example: 6 * 7
> q
Bye!

Check the logic with a table of tests

Because the logic layer is pure, you can write inputs and expected results as a table and check them in a loop. With pytest, @pytest.mark.parametrize turns each row into its own test. The table should cover normal cases, negative numbers, decimals, division by zero and malformed input.

For the interface layer, run a whole session with a scripted reader and check the lines passed to write. Neither kind of test needs a keyboard, so both run automatically in a CI pipeline.

test_table.py
import operator

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

cases = [((2, "+", 3), 5), ((-4, "-", 6), -10), ((2.5, "*", 4), 10.0)]
for (a, op, b), expected in cases:
    actual = OPS[op](a, b)
    status = "ok" if actual == expected else "FAIL"
    print(f"{status}: {a} {op} {b} = {actual}")

In real projects

In real projects

The calculator is small, but its shape is the same one found in CLI tools, chatbot command handlers, spreadsheet formula engines and pricing-rule engines: parse a command, dispatch through an allowlist, report domain errors with one exception type, and let the interface decide how to show them. Because the logic is separate, turning the CLI into a Tkinter GUI or a Flask API reuses evaluate_line() untouched.

If users should be able to type full expressions such as "(2 + 3) * 4", still do not reach for eval(). The standard approach is to parse with Python's ast module and write an evaluator that only accepts allowed node types (numbers and BinOp), or to use a well-tested parsing library.

Common mistakes

Common mistakes

Returning an error as a string

If divide() returns the string "Error!", every caller must check isinstance(result, str). Forget once and you either add a string to a number (TypeError) or store "Error!" in a database. Signal errors by raising an exception.

Catching everything with a bare except

except Exception: print("Invalid input") inside the loop also reports a NameError from a typo in your own code as "Invalid input", hiding the bug. Catch only the error type that users cause, CalculatorError.

Calling input() inside a logic function

With input() inside calculate(), a test hangs waiting for a keyboard, and the function cannot be reused in a GUI or web version. Accept values as parameters only.

Mini challenge

Add %, **, ans and history

Extend the calculator: add the % and ** operators, let the word "ans" stand for the previous result, and add a "history" command that lists successful calculations. run_lines() takes a list of lines and returns the list of output lines.

  • An exponent larger than 100 for ** raises CalculatorError (to avoid float overflow)
  • Both / and % refuse division by zero
  • Using ans before any calculation gives a clear error
  • Never call input(); run_lines() only returns the output list
calculator_plus.py
import operator


class CalculatorError(Exception):
    pass


def safe_power(a: float, b: float) -> float:
    # TODO: refuse exponents with abs(b) > 100, otherwise return a ** b
    ...


OPERATIONS = {
    # TODO: + - * / from the lesson, plus "%" and "**" (use safe_power)
}


def parse_operand(text: str, ans: float | None) -> float:
    # TODO: "ans" -> previous answer (error if None), else float(text)
    ...


def evaluate(line: str, ans: float | None) -> float:
    # TODO: split into 3 parts, check the operator, guard / and % by zero
    ...


def run_lines(lines: list[str]) -> list[str]:
    """Feed lines through the calculator and return what it would print."""
    # TODO: keep ans and a history list; "history" prints past results
    return []


session = ["ans + 1", "17 % 5", "ans ** 3", "2 ** 1000", "9 % 0", "ans / 4", "history"]
for shown in run_lines(session):
    print(shown)

Expected: First a "no previous answer yet" error, then = 2, = 8, the exponent error, the division-by-zero error and = 2, followed by the three successful calculations from history.

Show hint

Keep ans and history as local variables in run_lines(). Update ans and append to history only when a calculation succeeds; after an error ans keeps its previous value.

Show solution
calculator_plus.py
import operator


class CalculatorError(Exception):
    pass


def safe_power(a: float, b: float) -> float:
    if abs(b) > 100:
        raise CalculatorError("exponent too large (limit is 100)")
    return a ** b


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


def parse_operand(text: str, ans: float | None) -> float:
    if text == "ans":
        if ans is None:
            raise CalculatorError("no previous answer yet")
        return ans
    try:
        return float(text)
    except ValueError:
        raise CalculatorError(f"'{text}' is not a number") from None


def evaluate(line: str, ans: float | None) -> float:
    parts = line.split()
    if len(parts) != 3:
        raise CalculatorError("type: number operator number")
    left, op, right = parts
    if op not in OPERATIONS:
        raise CalculatorError(f"unknown operator '{op}'")
    a, b = parse_operand(left, ans), parse_operand(right, ans)
    if op in ("/", "%") and b == 0:
        raise CalculatorError("cannot divide by zero")
    return OPERATIONS[op](a, b)


def run_lines(lines: list[str]) -> list[str]:
    """Feed lines through the calculator and return what it would print."""
    ans = None
    history = []
    output = []
    for line in lines:
        if line == "history":
            output.extend(history or ["(empty)"])
            continue
        try:
            ans = evaluate(line, ans)
            history.append(f"{line} = {ans:g}")
            output.append(f"= {ans:g}")
        except CalculatorError as error:
            output.append(f"Error: {error}")
    return output


session = ["ans + 1", "17 % 5", "ans ** 3", "2 ** 1000", "9 % 0", "ans / 4", "history"]
for shown in run_lines(session):
    print(shown)

Quick quiz 1 / 3

In the lesson's calculator, what is shown when the user types "3 x 4"?

Quick quiz 2 / 3

Why is evaluating user text with eval() a bad idea?

Quick quiz 3 / 3

What is the main reason run_session takes read and write as parameters?

What to remember

  • Never run user text with eval(); dispatch through an operator allowlist dict
  • Keep the logic (parse, calculate) pure and confine input() and print() to the interface layer
  • Raise one exception type such as CalculatorError for user-fixable errors instead of returning strings
  • Passing read and write in makes even the interactive loop testable without a keyboard

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Calculator App (Enhanced) | Thuta Learning