Python Comments

Write # comments, comment out code, document functions with docstrings and keep notes accurate as code changes.

Lesson 3 of 107Beginner13 min read

A comment in Python starts with #. Python ignores everything from the # to the end of that line, so comments are notes for people, not instructions for the computer.

Python
# Rental bikes are serviced every 90 days because they are used daily.
service_days = 90   # an inline comment after code

Python has no special syntax for multiline comments: you write several lines that each start with #. Functions, classes and modules are documented with a different tool, the docstring, which tools such as help() can read. This lesson covers both, explains how to comment out code while testing, and shows the difference between comments that help and comments that just add noise. The examples come from a bicycle workshop documenting its maintenance rules.

Hash comments

A # that appears in code, outside any string, starts a comment. It can take a whole line or follow code on the same line:

Python
# Block comment: describes the next few lines
service_days = 90
label = "Rack #7"   # the # inside the quotes is part of the text

On the last line, the first # is inside a string, so it is ordinary text; only the second one starts a comment. Python decides by looking at whether the # is inside quotes, not by where it appears on the line.

Multiline comments are simply consecutive # lines. Most editors toggle them for a selection with Ctrl+/ (Cmd+/ on macOS). The same shortcut is the quickest way to comment out code temporarily while you test an idea. Delete commented-out code once the experiment is over; version control such as Git remembers old versions far better than a pile of disabled lines.

PEP 8 recommends a space after the # and at least two spaces before an inline comment.

Reason comments

The most valuable comments explain why the code does something, especially when the reason isn't visible in the code itself: a business rule, a workaround, a unit of measurement or a decision that looks odd at first glance.

Python
# Bad: repeats the code
service_days = 90   # set service_days to 90

# Good: records a reason the code can't express
service_days = 90   # manufacturer warranty requires a check every 90 days

The first comment adds nothing a reader can't see. The second tells a future maintainer that changing 90 has consequences.

If you need a comment to explain what a confusing line does, first try making the code clearer: choose a better variable name, split a long expression into named steps, or move it into a function with a descriptive name. Clear code with a few reason comments is easier to maintain than unclear code with many explanatory ones.

Docstrings

A docstring is a string literal placed as the first statement in a module, function, class or method. By convention it uses triple double quotes:

Python
def days_until_service(days_ridden):
    """Return how many days remain before the next service.

    A negative result means the bike is overdue.
    """
    return 90 - days_ridden

help(days_until_service)

Unlike a # comment, a docstring is kept by Python and stored on the function as days_until_service.__doc__. help(), editors and documentation generators all display it. Start with a one-line summary in the imperative ("Return...", "Calculate..."), then add details after a blank line if needed. PEP 257 describes the conventions.

You may see triple-quoted strings used as "multiline comments" in the middle of code. That works only because an unused string does nothing, but it is not a comment: Python still creates the string, and if it's the first statement of a function it becomes the docstring. Use # for comments and docstrings for documentation.

Maintenance

Comments are not checked by Python, so nothing warns you when they become false. A comment saying "service every 90 days" beside code that now uses 60 is worse than no comment, because the reader has to work out which one is right.

Treat comments as part of the code: when you change behaviour, read the nearby comments and docstrings and update them in the same edit. Code reviewers should check them too. Some notes have a deliberately short life: # TODO: remove after the spring sale marks work still to be done, and many editors list every TODO in a project. Clean them up when the work is finished, so they remain a reliable to-do list rather than background noise.

Independent practice and a worked check

Task: document a maintenance calculation with a reason comment and a short function docstring. Write a function that takes the number of days since a bike's last service and returns True if it is due. Rental bikes are due after 60 days and private bikes after 120.

Python
RENTAL_INTERVAL = 60    # rentals are ridden daily, so they wear faster
PRIVATE_INTERVAL = 120

def service_due(days_since_service, is_rental):
    """Return True if a bike needs servicing today."""
    limit = RENTAL_INTERVAL if is_rental else PRIVATE_INTERVAL
    return days_since_service >= limit

print(service_due(75, is_rental=True))    # True
print(service_due(75, is_rental=False))   # False

The comment records the reason for the difference; the docstring tells a caller what the function returns. For the worked check, ask what # represents in "Rack #7": it is a character in the string, because comment syntax only applies outside quotes.

Reference and next practice

The Python tutorial introduces comments, PEP 8 gives the style rules and PEP 257 covers docstring conventions. Next, learn the print() function in depth, and see PEP 8 style for the broader formatting rules. Practise with the Python exercises and the Python quiz.

Comments Summary

  • Hash comments: A hash outside a string starts a comment extending to the end of the line.
  • Reason comments: Useful notes explain assumptions or reasons that are not obvious from the instructions.
  • Docstrings: The opening string in a function, class or module documents its public purpose.
  • Maintenance: Comments need review when their related behavior changes.

Comments Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Comments in a small program

The program has one reason comment and one # that is not a comment at all.

Python
# Rental bikes are checked earlier because they are used daily.
service_days = 90
label = "Rack #7"
print(label, service_days)
Output
Rack #7 90
Line-by-line explanation
  1. Line 1A full-line comment explaining the business reason. Python skips it.
  2. Line 3"Rack #7" is a string, so the # and the 7 are printed as text.
  3. Line 4print() shows both values, separated by a space.
Example 2

A documented function

Python
def service_fee(hours, member=False):
    """Return the labour charge for a service, in pounds.

    Members get 20% off labour; parts are charged separately.
    """
    rate = 30
    fee = hours * rate
    if member:
        fee *= 0.8   # discount agreed with the cycling club in 2024
    return round(fee, 2)

print(service_fee(1.5))
print(service_fee(1.5, member=True))
print(service_fee.__doc__.splitlines()[0])
Output
45.0
36.0
Return the labour charge for a service, in pounds.
Line-by-line explanation
  1. Lines 2 to 5The docstring documents what the function returns and the rule a caller needs to know.
  2. Line 9An inline comment records where the 20% figure came from.
  3. Line 14The docstring is stored on the function and can be read at run time.

Common Comments Mistakes

Expecting # inside a string to start a comment

Don't
label = "Rack #7 # temporary"
print(label)        # prints: Rack #7 # temporary
Do
label = "Rack #7"   # temporary
print(label)        # prints: Rack #7

Everything inside the quotes is part of the string, including any # characters. Close the string before writing a comment.

Comments that repeat the code

Don't
count = count + 1   # add 1 to count
Do
count = count + 1   # include the demo bike, which isn't in the rental table

A comment should add information the reader can't get from the code: a reason, a constraint, a source or a warning.

Comments in Real Projects

Comments and docstrings in real projects

Open-source libraries rely on docstrings: the documentation you read for pandas or requests is largely generated from them, and the pop-up help in your editor comes from the same text. Teams often agree on a docstring style, such as Google or NumPy style, so parameter and return descriptions look the same everywhere.

In the bicycle workshop's code, the useful comments are the ones a new mechanic needs: why rental bikes have a shorter service interval, which supplier a price came from, and what "overdue" means. Linters such as Ruff can require a docstring on every public function, while code review catches comments that no longer match the code.

Comments FAQ

How do I write a multiline comment in Python?

Start each line with #. Python has no dedicated multiline comment syntax. Most editors add or remove # on every selected line with Ctrl+/ (Cmd+/ on macOS). Triple-quoted strings are sometimes used instead, but they are strings, not comments.

What is the difference between a comment and a docstring?

A comment starts with # and is discarded when Python reads the file. A docstring is a string placed first in a module, function or class; Python keeps it, and help() and editors display it. Use comments for notes about how code works and docstrings to describe what a function or class does for its callers.

Do comments slow down a Python program?

No. Comments are removed when Python reads the source, before any code runs, so they have no effect on speed. Docstrings are stored in memory, but the cost is negligible.

How do I comment out several lines quickly?

Select the lines and press Ctrl+/ (Cmd+/ on macOS) in VS Code, PyCharm and most other editors. The same shortcut removes the # again. For longer experiments, prefer a Git branch to large blocks of commented-out code.

Should every line of code have a comment?

No. Over-commenting makes code harder to read and the comments drift out of date. Comment the reasons, assumptions and surprises, write docstrings for functions others will call, and let clear names explain the rest.

Comments Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does # inside quoted text represent?

Multiple choicemedium

Which review concern is valid for comments?

Comments Quiz

2 questions to check what you learned.

  1. What does # inside quoted text represent?

    • A comment marker
    • A character in the string
    • Python ignores the distinction
  2. Which statement correctly describes docstrings?

    • The opening string in a function, class or module documents its public purpose.
    • Only the example output matters, not the rule
    • Every operation has the same behavior