Beginner · Console Apps · Packages: standard library only

Project 2: Simple Calculator

Build a safe command-line calculator that understands brackets, functions, variables and the last answer, using the ast module instead of eval().

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
simple-calculator/
  main.py   # safe expression engine + prompt loop

Step-by-step build

  1. Plan the engine (top of main.py). We need text in, number out. Python's eval() can run any code, so we use ast.parse and check every node ourselves.
  2. Make the operator tables. Dictionaries map ast.Add to operator.add and so on. Anything not in the table is rejected.
  3. Define CalcError. A tiny class that inherits Exception. All problems become CalcError so main.py handles only one kind.
  4. Write _eval. Check the node type: number, binary operation, unary minus, name or function call. Call _eval again on the parts (recursion).
  5. Write calculate and pretty. calculate parses the text and turns Python errors into friendly CalcError messages. pretty prints 4.0 as 4.
  6. Write the loop (bottom of main.py). Read a line, handle commands (help, history, quit), handle 'name = expression', then call calculate.
  7. Test bad input. Try 10 / 0, 7 //, and import os. Each should print an Error line and the calculator keeps running.

Complete source code

main.py
"""Safe calculator engine: evaluates maths text without using eval()."""
import ast
import math
import operator

# Allowed operators mapped to real functions
BINARY = {
    ast.Add: operator.add, ast.Sub: operator.sub,
    ast.Mult: operator.mul, ast.Div: operator.truediv,
    ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod,
    ast.Pow: operator.pow,
}
UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg}
# Allowed functions and constants
FUNCTIONS = {"sqrt": math.sqrt, "abs": abs, "round": round,
             "sin": math.sin, "cos": math.cos, "log": math.log10}
CONSTANTS = {"pi": math.pi, "e": math.e}


class CalcError(Exception):
    """Raised for any problem with the user's expression."""


def _eval(node, memory):
    """Walk the syntax tree and compute the value."""
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in BINARY:
        left = _eval(node.left, memory)
        right = _eval(node.right, memory)
        if type(node.op) is ast.Pow and abs(right) > 100:
            raise CalcError("Exponent is too big.")
        return BINARY[type(node.op)](left, right)
    if isinstance(node, ast.UnaryOp) and type(node.op) in UNARY:
        return UNARY[type(node.op)](_eval(node.operand, memory))
    if isinstance(node, ast.Name):
        if node.id in CONSTANTS:
            return CONSTANTS[node.id]
        if node.id in memory:
            return memory[node.id]
        raise CalcError(f"Unknown name: {node.id}")
    if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
            and node.func.id in FUNCTIONS and not node.keywords):
        args = [_eval(a, memory) for a in node.args]
        return FUNCTIONS[node.func.id](*args)
    raise CalcError("That is not allowed in a calculation.")


def calculate(text, memory=None):
    """Evaluate text like '2 * (3 + 4)'. Returns a number."""
    memory = memory if memory is not None else {}
    try:
        tree = ast.parse(text.strip(), mode="eval")
        return _eval(tree.body, memory)
    except ZeroDivisionError:
        raise CalcError("Cannot divide by zero.")
    except SyntaxError:
        raise CalcError("Invalid expression.")
    except (ValueError, TypeError, OverflowError):
        raise CalcError("Math error (check the numbers).")


def pretty(value):
    """Show 4.0 as 4 and long decimals with 10 digits at most."""
    if isinstance(value, float):
        if value == int(value) and abs(value) < 1e15:
            return str(int(value))
        return f"{value:.10g}"
    return str(value)


HELP = """Type a calculation such as 2 + 3 * 4 or sqrt(16).
Functions: sqrt abs round sin cos log   Constants: pi e
Use 'ans' for the last result, 'x = 5' to save a variable.
Commands: help, history, quit"""


def main():
    memory = {"ans": 0}
    history = []
    print("Simple Calculator. Type help for help.")
    while True:
        try:
            line = input("calc> ").strip()
        except EOFError:
            break
        if not line:
            continue
        if line == "quit":
            break
        if line == "help":
            print(HELP)
            continue
        if line == "history":
            for i, item in enumerate(history, 1):
                print(f"{i}. {item}")
            continue
        # Assignment like  x = 5 * 2
        name = None
        if "=" in line:
            name, _, line = (part.strip() for part in line.partition("="))
            if not name.isidentifier() or name in ("ans", "pi", "e"):
                print("Error: bad variable name.")
                continue
        try:
            result = calculate(line, memory)
        except CalcError as problem:
            print(f"Error: {problem}")
            continue
        memory["ans"] = result
        if name:
            memory[name] = result
        text = pretty(result)
        history.append(f"{line} = {text}")
        print(text if not name else f"{name} = {text}")
    print("Goodbye!")


if __name__ == "__main__":
    main()

Code explanation

Why not eval()

eval('__import__("os").system("...")') would run commands on your computer. By walking the syntax tree and allowing only maths nodes, user text can never run code.

Syntax tree

ast.parse('2 + 3 * 4', mode='eval') builds a tree where * is deeper than +. This gives correct operator order and brackets for free.

Recursion in _eval

For a BinOp node we evaluate the left and right child first, then apply the operator. The function calls itself until it reaches plain numbers.

Memory dictionary

memory holds 'ans' and user variables. ast.Name nodes are looked up in it, so 'pi * r ** 2' uses the saved r.

Error translation

calculate catches ZeroDivisionError, SyntaxError and others, and raises CalcError with simple words. The user never sees a traceback.

Assignment parsing

line.partition('=') splits at the first equals sign. Names are checked with isidentifier() so 'ans' or 'pi' cannot be overwritten.

Expected output

Simple Calculator. Type help for help.
calc> 14
calc> 20
calc> 2.5
calc> Error: Cannot divide by zero.
calc> 1024
calc> 13
calc> r = 3
calc> 28.27433388
calc> 56.54866776
calc> Error: Invalid expression.
calc> Error: Invalid expression.
calc> 1. 2 + 3 * 4 = 14
2. (2 + 3) * 4 = 20
3. 10 / 4 = 2.5
4. 2 ** 10 = 1024
5. sqrt(144) + 1 = 13
6. 3 = 3
7. pi * r ** 2 = 28.27433388
8. ans * 2 = 56.54866776
calc> Goodbye!

Common errors and solutions

Error: Error: Unknown name: x
Solution: You used a variable before saving it. Type x = 5 first.
Error: Error: Invalid expression.
Solution: Check brackets and operators, for example '7 //' is incomplete.
Error: ImportError: cannot import name 'calculate'
Solution: Only happens if you split the code into modules. Check the module file name and run Python from the project folder.
Error: Error: That is not allowed in a calculation.
Solution: Only numbers, + - * / // % **, brackets and the listed functions work. This is the safety feature.

Ideas to improve the project