Python Basics — Comments & Docstrings
Comments & Docstrings
Comments explain your code to other humans (and to your future self). Python ignores them completely — they exist purely for readability.
Single-Line Comments
Use the # symbol. Everything after # on that line is ignored:
# This is a comment
print("Hello") # This is an inline comment
Output:
Hello
When to Use Comments
# Good — explains WHY, not WHAT
# Calculate 15% tax for orders above $100
tax = subtotal * 0.15
# Bad — states the obvious
# Set x to 5
x = 5
Rule of thumb: Comment why you did something, not what the code does. Good code is self-explanatory about the “what.”
Multi-Line Comments
Python doesn’t have a dedicated multi-line comment syntax. Instead, use consecutive # lines:
# This function calculates the compound interest
# for a given principal, rate, and time period.
# Formula: A = P(1 + r/n)^(nt)
def compound_interest(principal, rate, time):
return principal * (1 + rate) ** time
Triple-Quoted Strings as Comments
Some developers use triple-quoted strings as multi-line comments:
"""
This is sometimes used as a
multi-line comment, but it's
technically a string literal.
"""
This works but is not recommended for comments. Triple quotes are meant for docstrings (see below).
Docstrings
A docstring is a special string that documents a function, class, or module. It’s the first statement inside the definition, enclosed in triple quotes:
def greet(name):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"
Accessing Docstrings
Python stores docstrings in a special __doc__ attribute:
def greet(name):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"
print(greet.__doc__)
Output:
Return a greeting message for the given name.
Using help()
The help() function displays the docstring:
help(greet)
Output:
Help on function greet in module __main__:
greet(name)
Return a greeting message for the given name.
Multi-Line Docstrings
For more complex functions, use multi-line docstrings:
def calculate_bmi(weight, height):
"""
Calculate Body Mass Index (BMI).
Args:
weight: Weight in kilograms.
height: Height in meters.
Returns:
BMI value as a float.
Example:
>>> calculate_bmi(70, 1.75)
22.86
"""
return round(weight / height ** 2, 2)
Docstring Styles
| Style | Used By | Example |
|---|---|---|
| Google projects | Args:, Returns:, Raises: |
|
| NumPy | Scientific Python | Parameters, Returns, with dashed sections |
| reStructuredText | Sphinx documentation | :param name:, :returns: |
The Google style is the most beginner-friendly and widely used in industry.
Comments vs Docstrings
| Feature | Comments (#) |
Docstrings ("""...""") |
|---|---|---|
| Purpose | Explain code logic | Document functions/classes/modules |
| Location | Anywhere in code | First line of function/class/module |
| Accessible at runtime | No | Yes (__doc__, help()) |
| Convention | Start with # |
Triple-quoted strings |
Best Practices
- Don’t over-comment — Good code with clear variable names needs fewer comments
- Update comments — Outdated comments are worse than no comments
- Always write docstrings for functions meant to be reused
- Keep comments concise — One or two lines is usually enough
# Bad — comment says what the code already says
# Increment counter by 1
counter += 1
# Good — comment explains a non-obvious decision
# Use binary search instead of linear for datasets > 10K items
result = binary_search(sorted_data, target)
Summary
- Use
#for single-line comments - Use consecutive
#lines for multi-line comments - Docstrings document functions, classes, and modules
- Access docstrings with
__doc__orhelp() - Comment why, not what
- Always write docstrings for reusable functions
Next up: IDE & Tools →