Python — Comments
Single-line comments
The hash symbol starts a comment that runs to the end of the line:
# Calculate the average score
total = sum(scores) / len(scores)
Use comments to explain why, not what. The code shows what's happening; comments explain the reasoning behind it.
Inline comments
x = 5 # Initialize with default value
Inline comments are useful for clarifying non-obvious values. Don't overuse them — too many inline comments clutter the code.
Docstrings — Python's documentation system
Triple-quoted strings at the start of a module, class, or function serve as documentation:
def calculate_average(scores):
"""
Calculate the arithmetic mean of a list of scores.
Args:
scores: A list of numerical values.
Returns:
The average as a float.
"""
return sum(scores) / len(scores)
Docstrings are accessible at runtime via help() and tools like Sphinx. They're not just comments — they're the foundation of Python's documentation ecosystem.
Module docstrings
At the top of a file, document what the module does:
"""
Data Processing Utilities
This module provides functions for cleaning, transforming,
and analyzing datasets. It depends on pandas and numpy.
"""
import pandas as pd
import numpy as np
def clean_data(df):
"""Remove rows with missing values."""
return df.dropna()
Docstring conventions
The community standard is Google-style docstrings:
def fetch_user(user_id, include_email=False):
"""
Fetch a user from the database by their ID.
Args:
user_id (int): The unique identifier for the user.
include_email (bool): Whether to include the user's email.
Defaults to False.
Returns:
dict: A dictionary containing user information.
Raises:
ValueError: If user_id is negative.
UserNotFoundError: If no user exists with the given ID.
"""
if user_id < 0:
raise ValueError("user_id must be non-negative")
# ... implementation
Other styles exist (NumPy, Sphinx), but Google-style is widely adopted and readable.
Multi-line comments
Python has no dedicated multi-line comment syntax. Options:
# Option 1: Multiple hash comments
# This is a long explanation
# that spans several lines
# of text describing the code.
# Option 2: Triple-quoted string (not recommended for pure comments)
"""
This is sometimes used as a comment
but it's actually a string expression.
The interpreter creates and discards it.
"""
Option 1 is preferred for non-documentation comments. Triple-quoted strings should be reserved for actual docstrings.
Comments and code quality
The best Python code needs very few comments because the syntax reads like English:
# Bad — comments that restate the code
# increment counter by one
counter += 1
# Good — comments that explain WHY
# Retry up to 3 times because the API is flaky
for attempt in range(3):
try:
response = api_call()
break
except ConnectionError:
continue
If you need a comment to understand what the code does, the code itself might need rewriting.
TODO and FIXME markers
# TODO: Add input validation for negative numbers
def calculate_area(width, height):
return width * height # FIXME: crashes when width is negative
Python doesn't have built-in TODO tracking, but most editors recognize these markers. Some projects use linters to collect TODOs into a report.
Docstrings and introspection
def greet(name, greeting="Hello"):
"""Greet a person with a custom message."""
print(f"{greeting}, {name}!")
# Access the docstring at runtime
print(greet.__doc__) # Greet a person with a custom message.
# Or use help()
help(greet)
Docstrings are part of the function — they're stored and accessible. This makes them more powerful than regular comments.
Extracting docstrings programmatically
import inspect
def process_data(data):
"""Process the input data."""
pass
# Get the docstring
doc = inspect.getdoc(process_data)
print(doc) # Process the input data.
Libraries like Sphinx read docstrings to generate HTML documentation. Good docstrings mean good docs without extra effort.
Common comment mistakes
# Bad: comments that are wrong
x = 5 # x is 10
# Bad: comments that are outdated
# This uses Python 2 syntax
print("Hello") # This is Python 3
# Bad: comments that are obvious
# Increment i
i += 1
# Good: comments that add value
# Convert to lowercase for case-insensitive comparison
name = name.lower()
Outdated or wrong comments are worse than no comments. If you change the code, update the comment too.
Mini Practice
- Write a function with a docstring that includes Args, Returns, and Raises
- Add a module-level docstring to a Python file
- Run
help()on a built-in function likelen— read its docstring - Find a TODO comment in a codebase and understand what it tracks
- Write a function and try to remove all comments — see if it's still readable
Next: the data types Python provides →
Related Topics
Frequently Asked Questions about Comments
What is Comments in Python?
Comments is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Comments?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Comments.
Why is Comments important in Python?
Comments is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.