Docstrings help explain what your code does in simple words. They make your code easier to understand for others and for yourself later.
Docstrings and documentation in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
""" Short description. More details if needed. """
Docstrings are written inside triple quotes (""" or '''), usually right after a function, class, or module definition.
They can be one line or multiple lines long.
Examples
Python
def greet(): """Say hello to the user.""" print("Hello!")
Python
def add(a, b): """ Add two numbers and return the result. Parameters: a (int): First number b (int): Second number Returns: int: Sum of a and b """ return a + b
Python
class Car: """A class to represent a car.""" def __init__(self, make, model): """Initialize make and model of the car.""" self.make = make self.model = model
Sample Program
This program defines a function with a docstring. It prints the result of multiplication and then prints the docstring itself.
Python
def multiply(x, y): """Multiply two numbers and return the product. Args: x (int or float): First number y (int or float): Second number Returns: int or float: Product of x and y """ return x * y print(multiply(4, 5)) print(multiply.__doc__)
Important Notes
Docstrings are accessible at runtime via the .__doc__ attribute.
Good docstrings improve code readability and help tools create documentation automatically.
Keep docstrings clear and concise, focusing on what the code does, not how.
Summary
Docstrings explain your code in simple words inside triple quotes.
Use them right after functions, classes, or modules to describe their purpose.
They help others and yourself understand and use your code better.
Practice
1. What is the main purpose of a
docstring in Python?easy
Solution
Step 1: Understand what docstrings are
Docstrings are special strings placed right after function, class, or module definitions to describe their purpose.Step 2: Identify the purpose of docstrings
They help explain what the code does, making it easier for others and yourself to understand.Final Answer:
To explain what a function, class, or module does -> Option CQuick Check:
Docstrings = Explanation [OK]
Hint: Docstrings describe code purpose inside triple quotes [OK]
Common Mistakes:
- Thinking docstrings run code
- Confusing docstrings with comments
- Using docstrings to store data
2. Which of the following is the correct way to write a docstring for a function in Python?
easy
Solution
Step 1: Identify correct docstring syntax
Docstrings use triple quotes (''' or """) placed immediately after the function header.Step 2: Check each option
def func(): '''This function does something''' uses triple single quotes right after the function header, which is correct. Options B and C use comments or double quotes incorrectly. def func(): // This is a docstring uses // which is not valid in Python.Final Answer:
def func(): '''This function does something''' -> Option DQuick Check:
Triple quotes after function = docstring [OK]
Hint: Docstrings use triple quotes right after function header [OK]
Common Mistakes:
- Using # instead of triple quotes
- Using single or double quotes only
- Placing docstring before function header
3. What will be the output of the following code?
def greet():
'''Return a greeting message.'''
return "Hello!"
print(greet.__doc__)medium
Solution
Step 1: Understand __doc__ attribute
The __doc__ attribute of a function returns its docstring, which is the string inside triple quotes right after the function header.Step 2: Check the function's docstring
The function greet has the docstring 'Return a greeting message.'. So, greet.__doc__ will output this string.Final Answer:
Return a greeting message. -> Option AQuick Check:
Function.__doc__ = docstring text [OK]
Hint: Use function.__doc__ to get its docstring text [OK]
Common Mistakes:
- Expecting function return value instead of docstring
- Confusing __doc__ with print output
- Assuming __doc__ is None if no docstring
4. Identify the error in the following code snippet:
def add(a, b):
"""Add two numbers and return the result."""
return a + b
medium
Solution
Step 1: Check docstring syntax
The docstring starts with triple double quotes """ but does not have a closing triple quote before the return statement.Step 2: Identify the error caused
Without closing triple quotes, Python treats the return line as part of the string, causing a syntax error.Final Answer:
Missing closing triple quotes for the docstring -> Option BQuick Check:
Docstrings need opening and closing triple quotes [OK]
Hint: Always close triple quotes in docstrings [OK]
Common Mistakes:
- Forgetting to close triple quotes
- Indenting return inside docstring
- Using single quotes inconsistently
5. You want to write a docstring for a function that calculates the area of a rectangle. Which of the following docstrings best follows good documentation practice?
hard
Solution
Step 1: Understand good docstring content
A good docstring clearly explains what the function does, its parameters, and what it returns.Step 2: Compare options
"""Calculate the area of a rectangle given width and height. Parameters: width (float): The width of the rectangle. height (float): The height of the rectangle. Returns: float: The area of the rectangle.""" provides a clear description, lists parameters with types, and explains the return value. Other options are too short or vague.Final Answer:
"""Calculate the area of a rectangle given width and height. Parameters: width (float): The width of the rectangle. height (float): The height of the rectangle. Returns: float: The area of the rectangle.""" -> Option AQuick Check:
Good docstrings = clear + parameters + return [OK]
Hint: Include purpose, parameters, and return in docstrings [OK]
Common Mistakes:
- Writing too short or vague docstrings
- Not mentioning parameters or return values
- Using incomplete sentences
