Summary
Perform division that never raises: return a default value on errors.
Problem statement
Division operations can raise exceptions (ZeroDivisionError, TypeError) when inputs are invalid. Implement safe_divide(a, b, default=None) that returns a/b as a float when possible. If division cannot be performed (b is zero, or inputs cannot be interpreted as numbers), return the provided default value instead of raising an exception. The function should handle integers and floats; do not coerce strings like '3' to numbers.
Task
Implement safe division that handles division by zero and invalid inputs gracefully.
Examples
normal division
Input
safe_divide(6, 3)
Output
2.0
Explanation
6 / 3 equals 2.0
division by zero uses default
Input
safe_divide(5, 0, default='error')
Output
error
Explanation
b is zero, so the function returns the provided default 'error'.
Input format
Call safe_divide(a, b, default=None). a and b are expected to be int or float; default may be any value to return on error.
Output format
Return a float result of division if successful, otherwise return the default value.
Constraints
Do not raise exceptions for invalid inputs; simply return default. If inputs are numeric types, perform true division and return a float.
Samples
Sample input 0
safe_divide(7, 2)
Sample output 0
3.5
Explanation 0
7 / 2 equals 3.5
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.