Exercise 1 — Building a Safe Calculator (Input Validation + Specific Exceptions)
Scenario
You are developing a tiny command-line calculator for a data-processing workflow. Because users might provide incorrect values or even attempt illegal operations such as dividing by zero, the calculator must be able to defend itself gracefully. Your task is to write a function that performs division safely, handling invalid numeric input and catching mathematical errors without stopping the program.
Task
Write a function called safe_divide(a, b) that tries to convert both inputs into floating-point numbers and performs the division. If the input cannot be converted, the function should catch ValueError or TypeError and print a clear message. If the division fails because the denominator is zero, the function should catch the ZeroDivisionError and inform the user. Whenever everything works, it should return the division result; when an error occurs, it should return None so the program can continue running.
The supplied test pairs cover success, zero division and invalid text. Also test None as an invalid input. Keep the function’s error result as None; its caller prints the final result line.
Starter Code
def safe_divide(a, b):
# TODO: convert to float and handle exceptions
pass
tests = [("10", "2"), ("5", "0"), ("abc", "3"), ("8.5", "2")]
for x, y in tests:
print(f"{x} / {y} = {safe_divide(x, y)}")Example Output
10 / 2 = 5.0
Error: cannot divide by zero.
5 / 0 = None
Error: 'abc' is not a valid number.
abc / 3 = None
8.5 / 2 = 4.25