livepython.net

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 number and read that number again.
  • The operator must be +, -, * or /. If it isn't, print Please type +, -, * or / and read the operator again.
  • If the operator is / and the second number is 0, print Cannot divide by zero instead 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.

Learn this firstChapter 17 · Python Input Validation: Ask Again with try except
solution.py
# write your code here

EXPECTED OUTPUT

1Result: 15.00
2Thank you for using the calculator

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.