Python Project: Calculator
It's time to build something real! In this project chapter you'll
progressively build a Python calculator — starting with a simple command-line version, refactoring it into a
clean OOP class with history and validation, extending it with scientific functions, and finally adding a
graphical interface with tkinter. Each version applies real Python
concepts you've learned — functions, classes, error handling, modules, and more — giving you a solid portfolio
project and a proven approach to building software iteratively.
Project Overview — Python Concepts Applied
This project is designed to reinforce everything you've learned. Here's the build roadmap and the Python concepts each version practices:
Version 1 — CLI Calculator with Functions
Start simple. A command-line calculator that takes input from the user, performs operations, and loops until the user quits. No classes — just clean functions.
# ── Calculator v1 — CLI with functions ────────────────
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def modulo(a, b):
if b == 0:
raise ValueError("Cannot modulo by zero")
return a % b
def power(a, b): return a ** b
OPERATIONS = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"%": modulo,
"**": power,
}
def get_number(prompt: str) -> float:
"""Get a valid number from the user."""
while True:
try:
return float(input(prompt))
except ValueError:
print("❌ Invalid number. Try again.")
def format_result(result: float) -> str:
"""Show int if whole number, else float."""
return str(int(result)) if result == int(result) else f"{result:.6g}"
def main():
print("╔══════════════════════════╗")
print("║ Python Calculator v1.0 ║")
print("╚══════════════════════════╝")
print(f"Operators: {', '.join(OPERATIONS)}")
print("Type 'q' to quit\n")
while True:
op = input("Operator (+ - * / % **): ").strip()
if op.lower() == "q": break
if op not in OPERATIONS:
print(f"❌ Unknown operator '{op}'"); continue
a = get_number("First number: ")
b = get_number("Second number: ")
try:
result = OPERATIONS[op](a, b)
print(f"✅ {a} {op} {b} = {format_result(result)}\n")
except ValueError as e:
print(f"❌ Error: {e}\n")
print("Goodbye! 👋")
if __name__ == "__main__":
main()
Version 2 — OOP Calculator Class
Refactor into a proper class. This version introduces custom exceptions, type
validation, a result property, and an operator dispatch pattern — the
foundation for all future versions.
# ── Calculator v2 — OOP class ─────────────────────────
class CalculatorError(Exception): pass
class DivisionByZeroError(CalculatorError): pass
class InvalidOperatorError(CalculatorError): pass
class InvalidInputError(CalculatorError): pass
class Calculator:
"""A clean OOP calculator with validation."""
OPERATORS = {"+", "-", "*", "/", "%", "**", "//"}
def __init__(self):
self._result = 0.0
@property
def result(self): return self._result
def _validate(self, a, b, op):
for val, name in [(a, "a"), (b, "b")]:
if not isinstance(val, (int, float)):
raise InvalidInputError(f"'{name}' must be a number, got {type(val).__name__}")
if op not in self.OPERATORS:
raise InvalidOperatorError(f"Unknown operator: '{op}'")
if op in ("/", "%", "//") and b == 0:
raise DivisionByZeroError("Cannot divide or modulo by zero")
def calculate(self, a: float, op: str, b: float) -> float:
"""Perform a calculation and store the result."""
self._validate(a, b, op)
ops = {
"+": lambda: a + b,
"-": lambda: a - b,
"*": lambda: a * b,
"/": lambda: a / b,
"%": lambda: a % b,
"**": lambda: a ** b,
"//": lambda: a // b,
}
self._result = ops[op]()
return self._result
def reset(self):
self._result = 0.0
def __repr__(self):
return f"Calculator(result={self._result})"
# ── Usage ─────────────────────────────────────────────
calc = Calculator()
print(calc.calculate(10, "+", 5)) # 15.0
print(calc.calculate(10, "**", 3)) # 1000.0
print(calc.result) # 1000.0
try:
calc.calculate(5, "/", 0)
except DivisionByZeroError as e:
print(f"Error: {e}") # Error: Cannot divide by zero
Version 3 — History, Memory & Undo
Extend the OOP calculator with a calculation history (list of named tuples), memory store, undo functionality, and optional JSON save/load for persistence across sessions.
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
import json
@dataclass
class Calculation:
"""Record of a single calculation."""
a: float
op: str
b: float
result: float
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def __str__(self) -> str:
return f"{self.a} {self.op} {self.b} = {self.result}"
class Calculator:
"""Calculator with history, memory and undo."""
def __init__(self):
self._result = 0.0
self._history: list[Calculation] = []
self._memory: float = 0.0
self._undo_stack: list[float] = []
def calculate(self, a: float, op: str, b: float) -> float:
self._undo_stack.append(self._result)
ops = {"+": a+b, "-": a-b, "*": a*b,
"/": a/b if b else (_ for _ in ()).throw(ZeroDivisionError())}
if b == 0 and op == "/":
raise ZeroDivisionError("Cannot divide by zero")
results_map = {"+": a+b, "-": a-b, "*": a*b,
"/": a/b, "%": a%b, "**": a**b, "//": a//b}
self._result = results_map[op]
self._history.append(Calculation(a, op, b, self._result))
return self._result
def undo(self) -> float | None:
"""Undo the last calculation."""
if self._undo_stack:
self._history.pop()
self._result = self._undo_stack.pop()
return self._result
return None
def memory_store(self): self._memory = self._result
def memory_recall(self) -> float: return self._memory
def memory_clear(self): self._memory = 0.0
def show_history(self, last_n: int = 5):
print("\n📋 Calculation History:")
if not self._history:
print(" (no history)"); return
for i, c in enumerate(self._history[-last_n:], 1):
print(f" {i}. {c}")
def save_history(self, path: str = "history.json"):
with open(path, "w") as f:
json.dump([c.__dict__ for c in self._history], f, indent=2)
print(f"✅ History saved to {path}")
# ── Usage ─────────────────────────────────────────────
calc = Calculator()
calc.calculate(10, "+", 5) # 15
calc.calculate(15, "*", 3) # 45
calc.calculate(100, "/", 4) # 25
calc.memory_store()
calc.show_history()
calc.undo() # back to 45
calc.save_history()
Version 4 — Scientific Calculator
Extend the class with scientific operations using Python's built-in math module — square root, logarithms, trigonometry, factorial, and
mathematical constants.
import math
class ScientificCalculator(Calculator): # extend v3 Calculator
"""Adds scientific operations to the base Calculator."""
# ── Constants ─────────────────────────────────────────
PI = math.pi # 3.14159...
E = math.e # 2.71828...
# ── Unary scientific operations ───────────────────────
def sqrt(self, n: float) -> float:
if n < 0: raise ValueError(f"sqrt of negative: {n}")
self._result = math.sqrt(n); return self._result
def log(self, n: float, base: float = math.e) -> float:
if n <= 0: raise ValueError(f"log of non-positive: {n}")
self._result = math.log(n, base); return self._result
def log10(self, n: float) -> float:
return self.log(n, 10)
def sin(self, degrees: float) -> float:
self._result = math.sin(math.radians(degrees))
return self._result
def cos(self, degrees: float) -> float:
self._result = math.cos(math.radians(degrees))
return self._result
def tan(self, degrees: float) -> float:
if degrees % 180 == 90: raise ValueError("tan undefined at 90°")
self._result = math.tan(math.radians(degrees))
return self._result
def factorial(self, n: int) -> int:
if n < 0 or n != int(n):
raise ValueError(f"Factorial needs non-negative int, got {n}")
self._result = math.factorial(int(n)); return self._result
def abs(self, n: float) -> float:
self._result = abs(n); return self._result
# ── Usage ─────────────────────────────────────────────
sci = ScientificCalculator()
print(sci.sqrt(144)) # 12.0
print(sci.sin(90)) # 1.0
print(sci.cos(0)) # 1.0
print(sci.log10(1000)) # 3.0
print(sci.factorial(5)) # 120
print(f"π = {ScientificCalculator.PI:.5f}") # 3.14159
print(sci.calculate(2, "**", 10)) # 1024 — inherits from Calculator
Version 5 — Safe Expression Evaluator
Let users type full expressions like 3 + 4 * 2 or
sqrt(16). Use Python's ast module to
safely parse and evaluate expressions — never using eval() directly on
user input.
import ast, math, operator
class SafeEvaluator(ast.NodeVisitor):
"""Safely evaluate arithmetic expressions using AST."""
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.FloorDiv: operator.floordiv,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
SAFE_FUNCS = {
"sqrt": math.sqrt,
"abs": abs,
"round": round,
"sin": math.sin,
"cos": math.cos,
"log": math.log,
"log10": math.log10,
"factorial": math.factorial,
}
SAFE_NAMES = {"pi": math.pi, "e": math.e, "inf": math.inf}
def evaluate(self, expr: str):
try:
tree = ast.parse(expr, mode="eval")
return self.visit(tree.body)
except (SyntaxError, KeyError, TypeError) as e:
raise ValueError(f"Invalid expression: {e}")
def visit_BinOp(self, node):
op = self.OPERATORS.get(type(node.op))
if op is None: raise ValueError("Unsupported operator")
return op(self.visit(node.left), self.visit(node.right))
def visit_UnaryOp(self, node):
op = self.OPERATORS.get(type(node.op))
if op is None: raise ValueError("Unsupported operator")
return op(self.visit(node.operand))
def visit_Constant(self, node): return node.value
def visit_Call(self, node):
name = node.func.id
fn = self.SAFE_FUNCS.get(name)
if fn is None: raise ValueError(f"Unknown function: {name}")
return fn(*[self.visit(a) for a in node.args])
def visit_Name(self, node):
if node.id in self.SAFE_NAMES: return self.SAFE_NAMES[node.id]
raise ValueError(f"Unknown name: {node.id}")
# ── Usage ─────────────────────────────────────────────
ev = SafeEvaluator()
print(ev.evaluate("3 + 4 * 2")) # 11 (operator precedence!)
print(ev.evaluate("(3 + 4) * 2")) # 14
print(ev.evaluate("sqrt(16) + pi")) # 7.14159
print(ev.evaluate("2 ** 10")) # 1024
print(ev.evaluate("factorial(5)")) # 120
# ev.evaluate("__import__('os').system('rm')") → ValueError!
Bonus — GUI Calculator with tkinter
Python's built-in tkinter library (no installation
needed) lets you build a desktop GUI calculator. This version uses grid layout, button callbacks, and the
SafeEvaluator from v5 for safe expression evaluation:
import tkinter as tk
from tkinter import font
class CalculatorApp(tk.Tk):
"""GUI Calculator using tkinter."""
BUTTONS = [
["C", "±", "%", "/"],
["7", "8", "9", "*"],
["4", "5", "6", "-"],
["1", "2", "3", "+"],
["0", ".", "⌫", "="],
]
def __init__(self):
super().__init__()
self.title("Python Calculator")
self.resizable(False, False)
self.configure(bg="#1e1e2e")
self._expr = ""
self._build_ui()
def _build_ui(self):
dsp_font = font.Font(size=28, weight="bold")
self._display = tk.Label(self, text="0", font=dsp_font,
bg="#1e1e2e", fg="#cdd6f4",
anchor="e", padx=10, pady=15)
self._display.grid(row=0, column=0, columnspan=4, sticky="ew")
btn_font = font.Font(size=16, weight="bold")
colors = {"C":"#f38ba8", "=":"#a6e3a1",
"+":"#89b4fa", "-":"#89b4fa",
"*":"#89b4fa", "/":"#89b4fa"}
for r, row in enumerate(self.BUTTONS, 1):
for c, label in enumerate(row):
bg = colors.get(label, "#313244")
btn = tk.Button(self, text=label, font=btn_font,
bg=bg, fg="#cdd6f4",
activebackground="#45475a",
relief="flat", bd=0,
width=4, height=2,
command=lambda l=label: self._press(l))
btn.grid(row=r, column=c, padx=2, pady=2, sticky="nsew")
self.bind("<Return>", lambda e: self._press("="))
def _press(self, label: str):
ev = SafeEvaluator()
if label == "C": self._expr = ""
elif label == "⌫": self._expr = self._expr[:-1]
elif label == "±": self._expr = f"-({self._expr})"
elif label == "=":
try:
result = ev.evaluate(self._expr)
self._expr = f"{result:.6g}"
except Exception:
self._expr = "Error"
else:
self._expr += label
self._display.config(text=self._expr or "0")
if __name__ == "__main__":
app = CalculatorApp()
app.mainloop()
tkinter is bundled with Python on Windows and macOS. On Linux, install
with sudo apt install python3-tk. Run the GUI script from your terminal or
IDE — it won't work in Jupyter Notebooks or most online compilers.
Practice Python Online — Free Compilers
Run and test the v1–v5 calculator versions in your browser. For the tkinter GUI version, you'll need a local Python installation or an IDE that supports GUI output.
- v1 (Functions): Build a CLI calculator using a dict of functions mapped to operators. Loop for input, validate with try/except, format results cleanly. ~30 lines.
- v2 (OOP): Refactor into a
Calculatorclass with custom exceptions hierarchy, input validation method, lambda-based operator dispatch, and aresultproperty. - v3 (History): Add a
Calculationdataclass for records, list-based history, stack-based undo, memory store/recall, and JSON persistence withsave_history(). - v4 (Scientific): Extend with inheritance —
ScientificCalculator(Calculator). Add sqrt, log, trig, factorial using themathmodule. Input in degrees, convert internally. - v5 (Expression): Build a safe expression evaluator using Python's
astmodule. Never use raweval()on user input — parse to AST and visit nodes. - GUI (tkinter): Build a desktop calculator with grid layout, colour-coded buttons, and
keyboard bindings. Uses
SafeEvaluatorfrom v5 for safe expression evaluation. - Key software engineering patterns applied: iterative development, single-responsibility functions, operator dispatch with dicts, inheritance for extension, dataclasses for records.
- This project is portfolio-ready. Extend it further: add a fraction mode, currency converter, unit converter, or integrate with an API for real exchange rates.
The dispatch table pattern (dict of functions) has several advantages over if/elif:
- O(1) lookup — dict lookup is faster than N if/elif checks
- Easier to extend — add a new operator by adding one dict entry, not inserting an elif
- Cleaner code — less repetition, functions defined separately and clearly
- Validation is trivial — just check if the key exists in the dict
This is a common Python pattern: replace switch-case / if/elif chains with dict-based dispatch.
eval() executes any Python code — if a malicious user types __import__('os').system('rm -rf /'), it will run as shell commands
with your program's permissions. This is a critical security vulnerability.
The safe alternative is to use Python's ast module — parse the expression into an Abstract Syntax Tree, then
selectively visit only the safe node types (numbers, basic operators, whitelisted functions).
Any unsafe node type raises an error.
A @dataclass instead of a plain dict or tuple:
- Named attributes —
c.resultinstead ofc[3]— much more readable - Auto-generates
__repr__and__eq__ - Type hints are enforced/documented
- Default values via
field(default_factory=...) - Custom
__str__for clean display
class ScientificCalculator(Calculator) means it inherits all
methods from Calculator — no code duplication. The scientific
class only adds new methods (sqrt, sin, log...) and can be used for all basic operations too:
sci = ScientificCalculator()
sci.calculate(2, "**", 10) # inherited!
sci.sqrt(144) # new!
This is the Open-Closed Principle — open for extension (new methods), closed for modification (original Calculator untouched).
Great portfolio extensions include:
- Currency Converter — integrate with the Open Exchange Rates API (requests library, Ch 52) to convert between currencies in real time.
- Unit Converter — add length, weight, temperature conversions. Use a dict of conversion factors — extends the dispatch pattern cleanly.
- Web Calculator — serve the calculator via a FastAPI/Flask endpoint. Accept expressions as JSON, return results. Combines Requests, APIs, and this project.
- Full GUI improvements — add keyboard shortcuts, history panel, memory display, and theme toggle to the tkinter version.
tk.Tk.
What does this mean?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.