Previous Lesson Current Lesson Next Lesson

Question 1

def f(l):
    """
    Convert a list's elements to string and return them.

    Parameters
    ----------
    l : list
        The list of elements to convert. Must be non-empty.

    Returns
    -------
    stringified : list
        The original list elements but stringified.

    Raises
    ------
    ValueError : the input list was empty.
    """
    out = []

    for i in l:
        out.append(str(i))

    if len(out) == 0:
        raise ValueError("No elements collected")

    return out

The first sentence describes what the function does. As was indicated in the problem, our “Parameters” section consists of one parameter l, which is a list. Based on the summary, we know the return value and its type.

Finally, the “Raises” section describes how we can get a ValueError, which is when the input list is empty. Although the code does not immediately show this. The reason is because we append every element from l in out. Thus, in order for out to be empty, l must be empty.

Your comments do not have to look exactly like this, but here, we make it very clear what’s happening and how the function works.

Question 2

def f(x):
    """
    Given an object, stringify it and return a list containing the stringified object twice.

    Parameters
    ----------
    x : object
        The object to stringify.

    Returns
    -------
    doubled : list
        A list of the stringified element, twice.
    """
    return [str(x), str(x)]

The structure is very similar, except we don’t have a “Raises” section. That’s because there are no explicit errors that are raised in the code (i.e. no raise keyword unlike in the first problem). Thus, that section is not needed.

Note that we assign x the type of object because it is the more generic type in Python. Everything in Python is an object, and since we did not specify any type in the problem, object is then the best type to give in the description.