Editor

Safe Division

#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:

  • If b is zero, return 'Cannot divide by zero'.
  • If a or b is not a number, return 'Numbers only'.

Examples

safe_divide(10, 4)   # returns 2.5
safe_divide(7, 0)    # returns 'Cannot divide by zero'
safe_divide('7', 2)  # returns 'Numbers only'

Note

a and b are never both a problem at the same time.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.