
The Docstring Oracle
A doctest is an example inside a docstring. It looks like an
interactive Python session. The doctest module runs each >>>
line and checks that the result matches the line below it:
def shout(word):
"""Return the word in capitals.
>>> shout("oil")
'OIL!'
"""
return word.upper() + "!"
Doctests are documentation that can't go out of date: if the
code changes, the example fails. On a real machine run
python -m doctest file.py -v, or call doctest.testmod().
Here we use doctest.run_docstring_examples(func, globals()),
which prints a report only when an example fails.
Pip tip: Doctests compare text, so
'OIL!'(with quotes, as the shell would show a string) is not the same asOIL!.
The bug report
fuel_gauge draws a 10-segment gauge, but its own docstring
examples fail. The bar comes out too long, and it overflows when the
level is above capacity.
Assignment
Fix the function body (not the examples!) so all three doctests pass.
Fix the function body (not the examples!) so all three doctests pass.
Press Run to try your code, then Check to test it.