Docstrings and Guard Clauses
~9 mincode completion
Write safe_average(numbers) that returns the mean, or 0.0 when the list is empty rather than crashing with ZeroDivisionError.
Examples
A normal list averages as expected
- Input
- safe_average([2, 4, 6])
- Output
- 4
An empty list returns 0.0 instead of raising ZeroDivisionError
- Input
- safe_average([])
- Output
- 0
A list containing only zero averages to 0.0, not an error
- Input
- safe_average([0])
- Output
- 0
Hints
Hint 1
Work directly with the arguments numbers and return the result rather than printing it.
Hint 2
Watch for this: divided by zero on empty.
Requirements
numbers: a list of numbers, possibly emptyReturn the mean, or 0.0 if there is nothing to average.
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~9 min
••••••
3 employers weight this skill
2 frontier labs, 1 AI product company. Top match scores 80.
Python
def safe_average(numbers):
"""
Mean of a list, tolerating an empty one.
Args:
numbers: a list of numbers, possibly empty
Returns:
The mean, or 0.0 if there is nothing to average.
"""
# YOUR CODE HERE
pass