#516 · Errors and exceptions · Beginner · 25 XP · about 4 min
Dividing can go wrong in two ways: dividing by zero raises a ZeroDivisionError, and dividing something that is not a number raises a TypeError. Write safe_divide(a, b) that returns a / b, but catches those two errors instead of letting the program crash:
b is zero, return 'Cannot divide by zero'.a or b is not a number, return 'Numbers only'.safe_divide(10, 4) # returns 2.5 safe_divide(7, 0) # returns 'Cannot divide by zero' safe_divide('7', 2) # returns 'Numbers only'
a and b are never both a problem at the same time.
First solves only, ranked by stars and then time.