Section 6.12 Docstrings
Back in Section 6.9 we created a function named
calculate_total
. Here it is again:def calculate_total(price, quantity):
subtotal = price * quantity
if quantity >= 20:
total = 0.90 * subtotal
elif quantity >= 10:
total = 0.93 * subtotal
else:
total = subtotal # no discount
return total
It’s probably been enough time since you read the page that you might not remember exactly what it was supposed to do. In a few weeks, you might remember even less. In order to help you (and other people reading your code) know what a function does, you add a docstring (short for “documentation string”) after the function header that explains the function’s purpose.
A docstring is always enclosed in triple quotes
"""
so that it can span multiple lines. Here is an activecode version of the program, using a docstring for the calculate_total
function:A docstring should start with a one-sentence summary of what the function does, followed by a blank line, followed by a more elaborate description. The ending triple quotes should be on a separate line.
There’s another reason to put docstrings in your functions: let’s say you have written a large number of functions to do statistical calculations, and you want to produce documentation so other people can use those functions too. There are programs that will go through your source code 1 and use the docstrings to automatically produce the documentation. That saves you a lot of work!
wiki.python.org/moin/DocumentationTools