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
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
Complete source code
main.py
What each file does
- main.py
- The whole program: data classes, validation, the command loop and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
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.txtand compare withtests/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
- 1Add named variables: 'let x = 5'.
- 2Add a 'undo' command that restores the previous ans.
- 3Support complex numbers with the cmath module.
Built and tested it yourself? Mark it to update your dashboard.