Skip to content
Foxipa
Code Completion 4 Challenges

Complete the doctest code

Practise writing stable docstring examples, documenting exceptions, distinguishing returned and printed output, and testing examples in text files.

Intermediate ~12 min read

Challenge 1

Add the expected prompt result for the discount example so doctest verifies the documented return value.

python Your answer
import doctest

def discounted_price(price, percent):
    """Return the price after a percentage discount.

    >>> discounted_price(50, 20)
    
    """
    return price * (1 - percent / 100)

result = doctest.testmod(verbose=True)
assert result.failed == 0

Press Ctrl⌘Enter to check your answer

Challenge 2

Document the type and stable message for the expected invalid-input exception.

python Your answer
import doctest

def first_word(text):
    """Return the first word from non-empty text.

    >>> first_word("")
    Traceback (most recent call last):
        ...
    
    """
    if not text:
        raise ValueError("text must not be empty")
    return text.split()[0]

result = doctest.testmod()
assert result.failed == 0

Press Ctrl⌘Enter to check your answer

Challenge 3

Add the output line produced by `print()` to the doctest transcript.

python Your answer
import doctest

def announce(job_id):
    """Print a queue confirmation.

    >>> announce("job-7")
    
    """
    print(f"Queued: {job_id}")

result = doctest.testmod()
assert result.failed == 0

Press Ctrl⌘Enter to check your answer

Challenge 4

Supply a Python string containing a valid prompt example in a temporary text file, then let testfile execute it.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory
import doctest

with TemporaryDirectory() as directory:
    path = Path(directory) / "guide.txt"
    path.write_text(
        ,
        encoding="utf-8",
    )
    result = doctest.testfile(str(path), module_relative=False, verbose=True)
    assert result.failed == 0

Press Ctrl⌘Enter to check your answer