Python Series track

Project 3 · Practice Projects

Project 3 — Calculator

Build a command-line calculator that parses infix expressions (+, -, *, /, **, %) and handles division-by-zero and invalid input gracefully.

Practice Projects1 min readFree lesson

Difficulty: Lv ★ | Prerequisites: Basics Week 4 + Week 9

Goal

Menu-based arithmetic operations + cumulative results

Differences from Basic Assignment

  • Basics Week 9 = Define 4 functions + menu
  • Here = Cumulative results + save history + handle division by zero

Requirements

  • Menu: 1.+ 2.- 3.* 4./ 5.Use previous result 6.Exit
  • Exception handling for division by zero
  • Print full history on exit

Challenge Task

  • Add **, %
  • Directly parse expression strings (eval prohibited)

Assignment

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution.pyPython
"""CLI Calculator — Menu Type + Cumulative Results"""

OPS = {
    "1": ("+", lambda a, b: a + b),
    "2": ("-", lambda a, b: a - b),
    "3": ("*", lambda a, b: a * b),
    "4": ("/", lambda a, b: a / b if b != 0 else None),
}

def main():
    history = []
    last = None
    while True:
        print("[Menu] 1.+ 2.- 3.* 4./ 5.Use previous result 6.Exit")
        choice = input("Select:").strip()
        if choice == "6":
            break
        if choice not in OPS:
            print("Invalid selection"); continue
        try:
            if last is not None and input(f"First number (previous result {last}):").strip() == "":
                a = last
            else:
                a = float(input("First number:"))
            b = float(input("Second number:"))
        except ValueError:
            print("Numbers only"); continue

        symbol, fn = OPS[choice]
        result = fn(a, b)
        if result is None:
            print("Cannot divide by 0")
            continue
        print(f"Result: {a} {symbol} {b} = {result}")
        history.append(f"{a} {symbol} {b} = {result}")
        last = result

    print("[Operation History]")
    for h in history:
        print(f"  {h}")

if __name__ == "__main__":
    main()

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now