A command calculator
In this project you build a calculator that you use by typing commands, one per line. Each command is a word that says what to do, followed by the numbers to do it with: add 3 4 adds 3 and 4, and sum 1 2 3 4 adds up any number of numbers. The calculator answers every line, and keeps going until you type quit.
When it's finished, a session looks like this. The person types these lines:
add 3 4
div ans 2
sum 1 2 3 4
mul ans ans
pow 2 8
div 5 0
add 2 three
history
quit
and the calculator answers them, with its prompt > in front of each typed line:
> add 3 4
7
> div ans 2
3.5
> sum 1 2 3 4
10
> mul ans ans
100
> pow 2 8
Error: unknown command pow
> div 5 0
Error: can't divide by zero
> add 2 three
Error: three is not a number
> history
1: add 3 4 = 7
2: div 7 2 = 3.5
3: sum 1 2 3 4 = 10
4: mul 10 10 = 100
> quit
Bye!
A mistake never stops the program: it gets a message that says what's wrong, and the next line is read as usual. ans stands for the last answer, and history lists every calculation that worked.
What you need
Everything up to module 18: while loops with break and continue (modules 9 to 12), strings and their indexes (module 11), functions that take parameters and return values, with the program's own code under if __name__ == "__main__": (modules 13 and 14), lists and for loops (modules 15 and 16), f-strings (module 17), and the string methods split and replace (module 18).
How you build it
Each milestone starts from your own code of the milestone before, and adds one thing to it:
- Four operations: a function for each operation, and
calculate, which answers one line. - Errors in commands: unknown commands and missing numbers get a message instead of a crash.
- Is it a number? Your own check for numbers, which also lets in decimals such as
2.5. - Any number of numbers:
sum,max,minandmeantake as many numbers as you type. - History: the calculator remembers what it calculated.
- The last answer:
ansin a command means the answer before it.
Some checks call your functions directly, as in the lessons, and others type lines into the whole program and compare everything it prints.
Milestones
- Four operations
- Errors in commands
- Is it a number?
- Any number of numbers
- History
- The last answer