Skip to content
Python project #08Beginner

Smart Calculator

A command-line calculator with operators, scientific functions, percentages, the previous answer, memory keys and history.

Estimated time
~2 hours to build
Files
4 files · 308 lines
Technologies
Python 3, math, lambda functions

Introduction

Building a calculator teaches parsing, dispatch tables and careful error handling. This one supports binary operators, functions such as sqrt and sin (in degrees), percentages, an 'ans' variable, memory keys and a history list.

Problem statement

Read lines such as '12 + 7', 'ans * 3', 'sqrt 81' and '15 % of 2400'. Support + - * / // % ^, functions sqrt, square, abs, round, sin, cos, tan, log, ln and fact, and the constants pi and e. Provide m+, m-, mr and mc memory commands and a history command. Division by zero, square roots of negatives, unknown operations and non-numbers must give friendly errors.

Objectives

  • Use dictionaries of functions as dispatch tables
  • Keep state (answer, memory, history) in a class
  • Validate input and catch errors
  • Format numbers neatly

Features

  • Binary operators including integer division and powers
  • Scientific functions with degree-based trigonometry
  • Percent-of calculations
  • ans, memory keys and history
  • Clear error messages

Concepts demonstrated

  • Dispatch tables
  • Classes with state
  • Exception handling
  • Number formatting

System architecture

BINARY and UNARY map operator and function names to callables. Calculator.evaluate recognises three shapes of input — '<a> <op> <b>', '<function> <a>' and '<p> % of <n>' — and validates special cases such as division by zero. run handles memory and history commands, stores the answer and records history. fmt prints whole numbers without decimals and others with up to ten significant digits.

Folder structure

TextProject tree
smart-calculator/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

133 lines
Pythonmain.py
"""Smart Calculator with history, memory and the previous answer (ans).
Examples:
12 + 7 binary operations: + - * / // % ^
ans * 3 ans is the last result
sqrt 81 functions: sqrt, square, abs, round, sin, cos, tan (degrees), log, ln, fact
15 % of 2400 percentages
m+ m- mr mc memory add / subtract / recall / clear
history show previous calculations
quit
"""
import math
import sys
BINARY = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"x": lambda a, b: a * b,
"/": lambda a, b: a / b,
"//": lambda a, b: a // b,
"%": lambda a, b: a % b,
"^": lambda a, b: a ** b,
}
UNARY = {
"sqrt": math.sqrt,
"square": lambda a: a * a,
"abs": abs,
"round": round,
"sin": lambda a: math.sin(math.radians(a)),
"cos": lambda a: math.cos(math.radians(a)),
"tan": lambda a: math.tan(math.radians(a)),
"log": math.log10,
"ln": math.log,
"fact": lambda a: math.factorial(int(a)) if a == int(a) else math.gamma(a + 1),
}
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def fmt(x: float) -> str:
if isinstance(x, int) or (isinstance(x, float) and x.is_integer() and abs(x) < 1e15):
return f"{int(x):,}"
return f"{x:,.10g}"
class Calculator:
def __init__(self):
self.ans = 0.0
self.memory = 0.0
self.history: list[str] = []
def number(self, token: str) -> float:
token = token.lower()
if token == "ans":
return self.ans
if token == "pi":
return math.pi
if token == "e":
return math.e
try:
return float(token.replace(",", ""))
except ValueError:
raise ValueError(f"'{token}' is not a number") from None
def evaluate(self, line: str) -> float:
tokens = line.split()
if len(tokens) == 4 and tokens[1] == "%" and tokens[2].lower() == "of":
return self.number(tokens[0]) / 100 * self.number(tokens[3])
if len(tokens) == 2 and tokens[0].lower() in UNARY:
value = self.number(tokens[1])
if tokens[0].lower() in ("sqrt", "log", "ln") and value < 0 or tokens[0].lower() in ("log", "ln") and value == 0:
raise ValueError(f"{tokens[0]} is undefined for {fmt(value)}")
if tokens[0].lower() == "fact" and (value < 0 or value > 170):
raise ValueError("fact needs a number from 0 to 170")
return UNARY[tokens[0].lower()](value)
if len(tokens) == 3 and tokens[1] in BINARY:
a, b = self.number(tokens[0]), self.number(tokens[2])
if tokens[1] in ("/", "//", "%") and b == 0:
raise ValueError("division by zero")
return BINARY[tokens[1]](a, b)
raise ValueError("use: <a> <op> <b>, <function> <a> or <p> % of <n>")
def run(self, line: str) -> str:
command = line.lower()
if command in ("m+", "m-"):
self.memory += self.ans if command == "m+" else -self.ans
return f"memory = {fmt(self.memory)}"
if command == "mr":
self.ans = self.memory
return f"ans = {fmt(self.ans)} (from memory)"
if command == "mc":
self.memory = 0.0
return "memory cleared"
if command == "history":
return "\n".join(f" {i}. {h}" for i, h in enumerate(self.history, 1)) or " (empty)"
result = self.evaluate(line)
if isinstance(result, float) and (math.isinf(result) or math.isnan(result)):
raise ValueError("result is too large")
self.ans = result
entry = f"{line} = {fmt(result)}"
self.history.append(entry)
return f"= {fmt(result)}"
def main() -> None:
calc = Calculator()
print("Smart Calculator (type 'quit' to exit)")
while True:
line = ask("calc> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
print(calc.run(line))
except (ValueError, OverflowError) as error:
print(f"Error: {error}")
print(f"{len(calc.history)} calculation(s). Last answer: {fmt(calc.ans)}")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Smart Calculator (type 'quit' to exit)
calc> 12 + 7
= 19
calc> ans * 3
= 57
calc> m+
memory = 57
calc> 100 / 8
= 12.5
calc> 7 // 2
= 3
calc> 2 ^ 10
= 1,024
calc> sqrt 81
= 9
calc> sqrt -4
Error: sqrt is undefined for -4
calc> 15 % of 2400
= 360
calc> sin 30
= 0.5
calc> fact 10
= 3,628,800
calc> 10 / 0
Error: division by zero
calc> 5 plus 3
Error: use: <a> <op> <b>, <function> <a> or <p> % of <n>
calc> abc * 2
Error: 'abc' is not a number
calc> mr
ans = 57 (from memory)
calc> ans - 7
= 50
calc> m-
memory = 7
calc> mr
ans = 7 (from memory)
calc> history
1. 12 + 7 = 19
2. ans * 3 = 57
3. 100 / 8 = 12.5
4. 7 // 2 = 3
5. 2 ^ 10 = 1,024
6. sqrt 81 = 9
7. 15 % of 2400 = 360
8. sin 30 = 0.5
9. fact 10 = 3,628,800
10. ans - 7 = 50
calc> quit
10 calculation(s). Last answer: 7
Input
12 + 7
ans * 3
m+
100 / 8
7 // 2
2 ^ 10
sqrt 81
sqrt -4
15 % of 2400
sin 30
fact 10
10 / 0
5 plus 3
abc * 2
mr
ans - 7
m-
mr
history
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • 12 + 7 = 19, then ans * 3 = 57 is stored in memory with m+.
  • sqrt -4, 10 / 0, '5 plus 3' and 'abc * 2' all produce errors without crashing.
  • After mr, ans - 7 = 50, m- leaves 7 in memory, and history lists 10 calculations.

Common errors

sin 30 prints -0.988

math.sin expects radians; convert degrees with math.radians first.

fact 2.5 raises an error

Use math.factorial only for whole numbers, or math.gamma(x + 1) for others.

Possible improvements

  • Parse full expressions with precedence (see the Expression Evaluator project)
  • Add unit-aware calculations
  • Save history to a file

Additional challenges

  1. 1Add named variables: 'let x = 5'.
  2. 2Add a 'undo' command that restores the previous ans.
  3. 3Support complex numbers with the cmath module.

Built and tested it yourself? Mark it to update your dashboard.