Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Docstrings and Guard Clauses

~9 mincode completion

Real functions have to cope with input that is not the happy case. The tidiest way is a guard clause: handle the awkward case first and return early, so the rest of the function does not have to think about it.

def average(numbers):
    if not numbers:          # empty list
        return 0.0
    return sum(numbers) / len(numbers)

Compare that with wrapping everything in an else. The guard version stays flat, and flat code is easier to read.

not numbers is worth understanding on its own. In a condition, Python treats empty things as false:

bool([])        # False       empty list
bool([0])       # True        one item, even though it is zero
bool("")        # False       empty string
bool(0)         # False

So if not numbers: reads as "if there is nothing here". It is more idiomatic than if len(numbers) == 0:.

Your task:

Write safe_average(numbers) that returns the mean, or 0.0 when the list is empty rather than crashing with ZeroDivisionError.

Example Tests

A normal list averages as expected

Input: {"numbers":[2,4,6]}

Expected: 4

An empty list returns 0.0 instead of raising ZeroDivisionError

Input: {"numbers":[]}

Expected: 0

A list containing only zero averages to 0.0, not an error

Input: {"numbers":[0]}

Expected: 0

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

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…