Safe Division with Exceptions
Easy
Write a function safe_divide(a, b) that returns a divided by b. If b is zero, return the string "Cannot divide by zero" instead of raising an error. If either input is not a number, return "Invalid input". Use try/except.
Input
Two values a and b (may not always be numbers).
Output
The division result, or an error message string.
Example
Input
safe_divide(10, 2), safe_divide(5, 0), safe_divide(5, "x")
Output
5.0 Cannot divide by zero Invalid input
Use try/except catching ZeroDivisionError and TypeError separately.
10 XP on solve
Back to lesson
Your Solution
Output
Click "Run" to execute your code...
⏳ Loading Python runtime (first run may take a few seconds)...
Log in to submit your solution and earn XP.