Python theorytheory 0/50 · 0%
Capstone · hard

45. Building a small CLI-style calculator (design)

Composing functions, validation, and error handling.

Real programs compose small, well-tested functions rather than one giant block. A calculator-like tool separates parsing, computing, and formatting concerns.

python
def parse_expression(tokens: list[str]) -> tuple[float, str, float]:
    a, op, b = tokens
    return float(a), op, float(b)

def compute(a: float, op: str, b: float) -> float:
    ops = {"+": lambda x, y: x + y, "-": lambda x, y: x - y,
           "*": lambda x, y: x * y, "/": lambda x, y: x / y}
    if op not in ops:
        raise ValueError(f"unsupported operator: {op}")
    return ops[op](a, b)

Dispatch tables (dict of operator -> function) replace long if/elif chains and are easy to extend. Validating input early with clear error messages (rather than letting a cryptic exception bubble up) makes tools far more usable.

Check your understanding

  1. 1. What pattern replaces a long if/elif chain for operators above?

  2. 2. Why raise `ValueError` for an unsupported operator instead of letting a KeyError bubble up?

  3. 3. Why separate parse_expression from compute?