Docstrings &
Comments
Learn how to write meaningful documentation directly inside your Python code, making it readable, maintainable, and professional.
Why Documentation Matters
Code is read far more often than it is written. Six months from now, you are the stranger reading your own code. Comments and docstrings are your notes to the future: they explain the why behind the what.
Two Tools: Comments vs Docstrings
Anatomy of a Documented Function
The # Comment: Rules & Best Practices
Docstrings: The Formal Standard
A docstring is the first statement inside a module, class, method, or function. Python stores it in the object's __doc__ attribute, making it available to help() and documentation generators.
Comments vs Docstrings: Key Differences
| # Comment | """Docstring""" | |
|---|---|---|
| Syntax | # text | """text""" |
| Placement | Anywhere in code | First statement of module/class/function |
| Runtime access | Stripped by Python | Stored in __doc__ |
| Audience | Developers reading source | Developers + users via help() |
| Purpose | Explain why | Explain what and how to use |
Popular Docstring Styles
Step-by-Step: Writing Great Docs
Example 1: Simple Function
"""Convert a Celsius temperature to Fahrenheit."""
return temp * 9 / 5 + 32
Example 2: Multi-line Docstring
"""Return the median of a list of numbers.
Args:
numbers (list[float]): Non-empty list
of numeric values.
Returns:
float: The median value.
Raises:
ValueError: If the list is empty.
"""
if not numbers:
raise ValueError("List is empty")
sorted_nums = sorted(numbers)
mid = len(sorted_nums) // 2
# Average two middle values for even-length lists
if len(sorted_nums) % 2 == 0:
return (sorted_nums[mid - 1] + sorted_nums[mid]) / 2
return sorted_nums[mid]
Example 3: Documenting a Class
"""A simple bank account with deposit and withdraw.
Attributes:
owner (str): Account holder's name.
balance (float): Current balance in USD.
"""
def __init__(self, owner, balance=0.0):
"""Initialize account with owner and optional balance."""
self.owner = owner
self.balance = balance
def deposit(self, amount):
"""Add amount to balance. Returns new balance."""
self.balance += amount
return self.balance
Good vs Bad Comments
x = x + 1
# set name to Alice
name = "Alice"
x = x + 1
# Default for demo mode
name = "Alice"
Common Mistakes to Avoid
Summary: Quick Reference
| Comment | One-Line Docstring | Multi-Line Docstring | |
|---|---|---|---|
| Syntax | # text | """text""" | """text\n\nArgs:...""" |
| Where | Any line | Simple functions | Complex functions/classes |
| Answers | Why? | What does it do? | What, how, edge cases? |
| Runtime? | No | Yes (__doc__) | Yes (__doc__) |
| Tools | Source reading | help(), IDE tooltips | Sphinx, pdoc, mkdocs |
Question 1 of 5
What is the primary difference between a comment and a docstring in Python?
Question 2 of 5
def greet(name):
# Return a greeting string
return f"Hello, {name}!"
What is wrong with the comment in this function?
Question 3 of 5
Where must a docstring be placed for Python to recognize it as documentation?
Question 4 of 5
Which of the following is a well-written inline comment?
Question 5 of 5
def is_even(n):
"""Check if n is even.
Args:
n (int): The number to check.
Returns:
bool: True if n is even, False otherwise.
"""
return n % 2 == 0
Which documentation style is used in the function above?