In this lesson, you will learn how to create standardized docstrings to explain what your functions do, the data they expect, and what they return.
What is a Docstring?
While comments (starting with #) are great for explaining the "how" inside your code, a docstring is a special type of documentation used to explain the "what" and "why" of a function. It is placed immediately below the function definition using triple quotes (""").
Unlike regular comments, docstrings are stored by Python, which allows your IDE to display helpful "tooltips" whenever you hover over your function name elsewhere in your code.
Standardizing Your Documentation
A well-written docstring typically follows a pattern: a one-line summary, a description of parameters, and a description of the return value. Here is how you can document a function that adds two numbers:
def calculate_sum(a, b):
"""
Calculates the sum of two numbers.
Parameters:
a (int/float): The first number to add.
b (int/float): The second number to add.
Returns:
int/float: The total sum of a and b.
"""
return a + b
Why Use Them?
By using this structure, you turn your code into a professional-grade tool. When you or a colleague hover over calculate_sum in an IDE, the editor will automatically read this docstring and display the parameter information, saving you the trouble of remembering exactly how the function works weeks later. It acts as a built-in user manual for every function you write.
Using triple quotes also allows the text to span multiple lines, making it easy to read both in your source file and in the documentation tools that generate help pages for your project. By adopting this habit now, you ensure that your code is not just functional, but also discoverable and easy to maintain.
Key Takeaway: Docstrings are multi-line strings placed immediately after a function definition to provide clear, accessible documentation for parameters and return values that IDEs can automatically display.