159. Python Program to Make a Safe Calculator
HardSafe input
Overview
The chapter challenge: put safe input loops, several error types, else and finally together.
Problem Statement
Read a first number, an operator, and a second number, one per line. Print the result with 2 decimal places, like this for 12, + and 3:
Result: 15.00
The calculator must never crash:
- Numbers may have decimals. If a number is not valid, print
Please type a numberand read that number again. - The operator must be
+,-,*or/. If it isn't, printPlease type +, -, * or /and read the operator again. - If the operator is
/and the second number is 0, printCannot divide by zeroinstead of a result.
In every case, the last line is:
Thank you for using the calculator
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Input
One value per line: the first number, the operator, the second number, with retries where a value is bad. Example:
abc
10
x
/
4
Output
The output for that example:
Please type a number
Please type +, -, * or /
Result: 2.50
Thank you for using the calculator
The tests try 5 different inputs.