Reading history

Python Comments: Single-Line, Multi-Line and Docstrings

6 min read 4 views

Learn how to write Python comments with #, how to comment out code, how docstrings work, and what makes a comment useful. Runnable examples and exercises.

A comment is a note in your code that Python skips. Comments are for people: your teammates, your teacher, or you in three months when you have forgotten why a line exists. In Python, a comment starts with #.

In this lesson you will learn

  • How to write full-line and end-of-line comments
  • How to write comments that span several lines
  • How to switch a line off by commenting it out
  • What docstrings are and how Python uses them
  • How to tell a helpful comment from a useless one

Single-Line Comments

Everything after a # on a line is ignored. A comment can take a whole line, or sit at the end of a line of code.

# Convert a price from US dollars to Bangladeshi taka
usd = 25
rate = 122            # taka per dollar (example rate)
taka = usd * rate
print(taka)

Output

3050

The first line explains what the program does. The comment beside rate explains what the number means, which is not obvious from 122 alone. PEP 8 asks for at least two spaces before an end-of-line comment and one space after the #.

A # inside quotes is not a comment

In print("Item #5"), the # is part of the text, so Python prints Item #5. A comment only starts at a # outside a string.

Comments Over Several Lines

When a note needs three or four lines, give every line its own #. That is the only comment style Python offers; C programmers looking for an opening and closing pair will not find one.

# Delivery charge rules:
#   orders of 1000 taka or more travel free,
#   smaller orders inside Dhaka pay 60 taka,
#   orders outside Dhaka pay 120 taka.

Most editors comment or uncomment a group of selected lines with one shortcut: Ctrl + / on Windows and Linux, or Cmd + / on macOS.

You may see programmers use a triple-quoted string as a block comment. Python does ignore a string that is not stored anywhere, but this is not a real comment, and it can be mistaken for a docstring. Stick with # for comments.

Commenting Out Code

Putting # in front of a line of code switches it off without deleting it. This is handy when testing.

print("Step 1: load data")
# print("Step 2: send email")   <- switched off while testing
print("Step 3: save report")

Output

Step 1: load data
Step 3: save report

Step 2 did not run. Remove the # and it runs again. Use this for quick experiments only. Before you share or publish code, delete lines you no longer need; version control (such as Git) keeps the old copy for you.

Docstrings: Documentation Python Can Read

A docstring is a string in triple quotes placed on the first line inside a function, class or file. Unlike a comment, Python keeps it. Tools like help() and code editors show it to anyone who uses your function.

def bmi(weight_kg, height_m):
    """Return body-mass index, rounded to one decimal place.

    weight_kg: weight in kilograms
    height_m:  height in metres
    """
    return round(weight_kg / height_m ** 2, 1)


print(bmi(68, 1.72))
print(bmi.__doc__.splitlines()[0])

Output

23.0
Return body-mass index, rounded to one decimal place.

The docstring is stored in the function’s __doc__ attribute. Try help(bmi) in the interactive shell and Python prints the whole docstring. A good docstring starts with one short line saying what the function returns or does, followed by details if needed.

Comment (#)Docstring ("""...""")
Kept by Python?No, thrown awayYes, stored in __doc__
WhereAnywhereFirst line inside a function, class or file
ExplainsWhy or how a piece of code worksWhat the function does and how to call it
Read byPeople reading the sourcePeople using the code, through help() and editors

What Makes a Comment Useful?

A comment should add something the code cannot say by itself. The most useful comments explain why.

count = 0

# Bad: repeats what the code already says
count = count + 1        # add 1 to count

# Good: explains why the value was chosen
retries = 3              # the payment API often fails once on slow networks

print(count, retries)

Output

1 3

The first comment wastes the reader’s time: the code already says “add 1”. The second one records a decision nobody could guess from the code. Without it, a teammate might “simplify” retries to 1 and bring back the bug.

  • Write: reasons, warnings, units (kg, taka, seconds), sources of magic numbers, and links to bug reports.
  • Skip: comments that repeat the code, and old comments that no longer match it. A reader trusts a comment, so an outdated one sends them in the wrong direction.
  • Prefer clear names: delivery_fee_taka = 60 needs no comment at all.

Special Comment Lines

  • # TODO: add input validation marks unfinished work. Many editors list every TODO in a project.
  • #!/usr/bin/env python3 on the very first line (the “shebang”) lets macOS and Linux run the file directly as ./script.py.
  • # type: ignore and # noqa tell type checkers and linters to skip a line. You will meet these in bigger projects.

Common Mistakes

  1. Using // or /* */. Those are C, Java and JavaScript comments. In Python, /* */ is a SyntaxError, and // is worse: it means floor division, so total = 10 // half price fails with a confusing error, or quietly divides if the words happen to be valid names.
  2. Forgetting to update the comment when the code changes. The comment then lies to the next reader.
  3. Leaving large blocks of commented-out code. It clutters the file and hides the real program.
  4. Putting a docstring in the wrong place. It must be the first statement inside the function; anywhere else it is just an unused string.

Practice Exercises

Exercise 1. Add a comment above this code explaining what it calculates, and an end-of-line comment giving the unit of speed.

distance = 240
time = 4
speed = distance / time
print(speed)
Show answer
# Average speed of the Dhaka to Sylhet bus trip
distance = 240
time = 4
speed = distance / time   # km per hour
print(speed)

Exercise 2. What does this program print?

print("A")
# print("B")
print("C #1")
Show answer

It prints A and then C #1. The middle line is commented out, and the # in the last line is inside the text.

Exercise 3. Write a function area(width, height) with a one-line docstring, returning width × height.

Show answer
def area(width, height):
    """Return the area of a rectangle."""
    return width * height

Frequently Asked Questions

How do I write a multi-line comment in Python?

Start each line with #. Most editors do this for you when you select lines and press Ctrl + /.

Do comments slow down a Python program?

No. Python drops comments when it reads the file, so they have no effect on speed.

Is a triple-quoted string a comment?

Not exactly. It is a string. As the first line of a function it becomes a docstring; elsewhere Python creates it and throws it away. Use # for normal comments.

How many comments should I write?

There is no fixed number. Use clear names first, then add comments where a reader would otherwise ask “why?”.

Summary

  • A comment starts with # and runs to the end of the line.
  • For several lines, start each one with #.
  • Commenting out a line switches it off without deleting it.
  • Docstrings in triple quotes document functions and are readable with help().
  • Good comments explain why; clear names reduce the need for comments.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *