Academic Block

Python Comments & DocstringsGet Certified

What Are Comments in Python?

A comment is a note written inside a program for people to read. Python ignores comments completely, so they never change what the program does. Their only job is to explain the code to you, to your teammates, and to the future version of yourself who will open the file again in six months and wonder what it was supposed to do.

Python has two documentation tools that look similar but serve different purposes. Comments start with a # and explain how or why a piece of code works. Docstrings are special strings written inside a module, class, or function that describe what it is for. Python keeps docstrings in memory, so tools like help() can show them while the program runs.

  • Comments: start with #, run to the end of the line, and are thrown away by the interpreter.
  • Inline comments: sit on the same line as a statement, after the code.
  • Docstrings: triple-quoted strings placed as the first statement of a module, class, or function.
  • The __doc__ attribute: the place where Python stores a docstring so it can be read at run time.
  • PEP 8 and PEP 257: the official style guides for comments and docstrings.

Single-Line Comments with #

A comment begins at the hash symbol # and continues to the end of that line. Everything after the # is ignored by Python. A comment can sit on a line of its own, or it can follow a statement on the same line. PEP 8 recommends a space after the #, and at least two spaces between the code and an inline comment.

  • Block comment: a line that contains only a comment. Use it to explain the section of code that follows.
  • Inline comment: a comment after a statement on the same line. Use it sparingly, and only when it adds useful information.
  • No closing symbol: a comment ends automatically when the line ends.
  • Blank lines: comments and empty lines can appear anywhere without affecting indentation rules.

Try It: Block and Inline Comments

This program calculates the area of a rectangle. Click Test My Code to run it, then change the width and height, and run it again. The output stays correct because the comments never take part in the calculation.

What this code does: It starts with a block comment that states the purpose of the program. It stores a width and a height, multiplies them, and prints the area. One line carries an inline comment that names the formula.
# Calculate the area of a rectangle
width = 8
height = 5
area = width * height  # area = width x height
print("Area:", area)

Multi-Line Comments

Python has no special syntax for a comment that spans many lines. The normal way is to start every line with its own #. Most editors can add or remove # from several selected lines at once, usually with Ctrl + /.

You may also see a triple-quoted string used as a multi-line comment. This is not a real comment. Python reads it as a string, creates it, and throws it away. It works, but it is not the recommended style. Triple quotes are meant for docstrings, which you will meet later in this lesson.

Try It: A Comment Spread Over Several Lines

The header at the top is made of three comment lines, one # on each. Click Test My Code and notice that only the calculation produces output.

What this code does: It uses three comment lines as a program header. It then adds an 18% tax to a price and prints the total. The blank line separates the header from the code.
# Program: Shopping bill
# Author: A. Student
# Purpose: add tax to a price

price = 200
tax_rate = 0.18
total = price + price * tax_rate
print("Total:", total)

Commenting Out Code and the # Inside Strings

Programmers often put a # in front of a line of code to disable it temporarily without deleting it. This is called commenting out code. It is useful while testing and debugging, but you should delete old code that you no longer need, because version control systems such as Git remember it anyway.

A # only starts a comment when it is outside a string. A hash symbol inside quotation marks is just an ordinary character, so Python prints it like any other text.

Try It: Disabled Code and a # Inside a String

Click Test My Code. The second print() is commented out, so it does not run. Remove the # in front of it and run the program again to see it work.

What this code does: It stores a sentence that contains a # inside quotation marks and prints it. A real comment follows on the same line. One print() call is commented out, so it is skipped, and a final line prints a message.
message = "Use # to start a comment"  # the # in the quotes is just text
print(message)
# print("This line is disabled")
print("Done")

Docstrings: Documentation Inside Your Code

A docstring (documentation string) is a string literal written as the very first statement inside a module, class, or function. Docstrings describe what the code does and how to use it. Unlike comments, Python stores a docstring on the object, so it is available at run time through the __doc__ attribute and the built-in help() function. Editors and documentation tools also read them to show hints while you type.

  • Triple double quotes: write docstrings with """, as recommended by PEP 257.
  • First statement only: a string that appears later in the body is not a docstring.
  • One-line docstring: a short summary where the closing quotes are on the same line, such as """Return the square of a number.""".
  • Multi-line docstring: a summary line, then a blank line, then more details such as the arguments and the return value.
  • Imperative mood: write the summary as a command, such as “Return the total”, not “Returns the total”.

Try It: A Function Docstring and __doc__

Click Test My Code. The program calls the function and then prints its docstring. Change the text of the docstring and run it again to see the new text appear.

What this code does: It defines a function square() with a one-line docstring. It prints the square of 6, and then prints the function’s __doc__ attribute, which holds the docstring text.
def square(n):
    """Return the square of a number."""
    return n * n

print(square(6))
print(square.__doc__)

Try It: A Multi-Line Docstring with input()

The Program Input box is already filled with a weight of 70 and a height of 1.75, one value on each line. Click Run Code straight away, then try other values.

What this code does: It defines a function that calculates body mass index and documents it with a multi-line docstring that has a summary, an arguments section, and a returns section. The program then reads a weight and a height with input() and prints the BMI.
def bmi(weight, height):
    """Calculate body mass index.

    Args:
        weight: weight in kilograms.
        height: height in metres.

    Returns:
        The BMI rounded to 1 decimal place.
    """
    return round(weight / height ** 2, 1)

weight = float(input("Weight in kg: "))
height = float(input("Height in m: "))
print("BMI:", bmi(weight, height))

Try It: Module, Class and Method Docstrings

Docstrings can document a whole file (a module), a class, and each method inside a class. Click Test My Code to print all three and to see the class in action.

What this code does: It starts with a module docstring, defines a class Greeter with a class docstring, and gives its hello method a docstring. It then prints the three docstrings through __doc__ and finally calls the method.
"""Utility module for greeting people."""

class Greeter:
    """A simple class that greets a person."""

    def hello(self, name):
        """Print a greeting for the given name."""
        print("Hello,", name)

print(__doc__)
print(Greeter.__doc__)
print(Greeter.hello.__doc__)
Greeter().hello("Asha")

Comments vs Docstrings

  • Purpose: a comment explains how or why a piece of code works. A docstring explains what a module, class, or function does.
  • Syntax: a comment starts with #. A docstring is a triple-quoted string in a fixed position.
  • At run time: Python discards comments. Python keeps docstrings in __doc__.
  • Audience: comments are for people who read the source code. Docstrings are also for people who only use the code, through help() and editor hints.
  • Placement: a comment can appear on any line. A docstring must be the first statement of its module, class, or function.

Writing Good Comments

A good comment tells the reader something the code cannot say by itself. A bad comment only repeats the code in English, and when the code changes it can quietly become wrong. Compare these two lines:

  • Weak: x = x + 1 # add 1 to x. The comment repeats what is already obvious.
  • Better: retries = retries + 1 # count the failed login attempt. The comment gives the reason.
  • Explain why: describe the intention, a business rule, or a surprising choice.
  • Keep comments up to date: a wrong comment is worse than no comment.
  • Choose clear names first: good variable and function names often remove the need for a comment.
  • Use markers: notes such as # TODO: and # FIXME: help you find unfinished work later.
  • Keep lines short: PEP 8 suggests wrapping comments at about 72 characters.

Try It: Useful Comments and a TODO Marker

The Program Input box is already filled with the price 250. Click Run Code, then try other prices. Notice that the comments explain why things are done and that one debug line is switched off.

What this code does: It reads a price, applies a fixed 10 percent discount, and prints the new price. A TODO comment records future work, an inline comment explains a value, and a commented-out debug line can be switched on when needed.
# TODO: read the discount from a file later
discount = 10  # percent, fixed for now

price = float(input("Enter the price: "))

# Reduce the price by the discount percentage
final_price = price - price * discount / 100
# print("DEBUG:", final_price)  # remove the first # to inspect the value

print("Price after discount:", final_price)
Tip: Before you write a comment, ask yourself whether a clearer variable name or a small function would make the comment unnecessary. If the code still needs an explanation, write the comment.

Special Comments You May Meet

  • Shebang line: #!/usr/bin/env python3 on the first line of a script tells Unix-like systems which interpreter should run the file.
  • Encoding declaration: a line such as # -*- coding: utf-8 -*- names the file encoding. It is rarely needed in Python 3 because UTF-8 is the default.
  • Tool directives: comments such as # noqa or # type: ignore are read by linters and type checkers. Python itself still ignores them.

Common Mistakes with Comments and Docstrings

  • Forgetting the #: writing a note without # makes Python read it as code and raises a SyntaxError or a NameError.
  • Unclosed triple quotes: a docstring that never closes causes a SyntaxError such as “unterminated triple-quoted string literal”.
  • Docstring in the wrong place: a string that is not the first statement of the function body is only an unused string, so __doc__ will be None.
  • Using a docstring as a comment: a triple-quoted string in the middle of the code is not a comment. It is wasteful and confusing.
  • Outdated comments: changing the code and forgetting to update the comment leaves the reader with false information.
  • Over-commenting: a comment on every line makes the code harder to read, not easier.
  • Commenting out an indented block: if you comment out only the header of an if or for statement, the indented lines below it cause an IndentationError.

Key Takeaways

  • A comment starts with #, runs to the end of the line, and is ignored by Python.
  • Python has no separate multi-line comment syntax. Use one # per line.
  • A # inside a string is ordinary text, not a comment.
  • A docstring is a triple-quoted string that is the first statement of a module, class, or function.
  • Python keeps docstrings in __doc__, and help() displays them, but comments are discarded.
  • Use comments to explain why, use docstrings to explain what, and keep both accurate and short.
  • Follow PEP 8 for comments and PEP 257 for docstrings.

Frequently Asked Questions

What is a comment in Python?

A comment is a note written in the source code for human readers. It starts with a # symbol and continues to the end of the line. Python ignores comments completely, so they do not change how the program runs.

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

Python has no dedicated multi-line comment syntax. Start each line with its own # symbol. Most code editors can add or remove the # from several selected lines at once. A triple-quoted string is sometimes used instead, but it is really a string and not a comment.

What is a docstring in Python?

A docstring is a string literal written as the first statement of a module, class, or function to describe what it does. Python stores it in the __doc__ attribute, so it can be read while the program runs and shown by the help() function and by code editors.

What is the difference between a comment and a docstring?

A comment starts with # and is thrown away by Python. It explains how or why the code works. A docstring is a triple-quoted string in a fixed position that explains what a module, class, or function does. Python keeps docstrings in memory, so they can be accessed through __doc__ and help().

Should I use single or double quotes for a docstring?

PEP 257 recommends triple double quotes, written as “””, even for one-line docstrings. Triple single quotes also work, but triple double quotes are the standard that most Python code and tools follow.

How can I read a docstring?

Use the __doc__ attribute, for example print(my_function.__doc__), or call help(my_function) in an interactive session. Both display the docstring of the function, class, or module.

Can I put a comment on the same line as code?

Yes. This is called an inline comment. Write the code, add at least two spaces, then # and a space followed by the note. Use inline comments sparingly, and only when they explain something that is not obvious from the code.

Does a # inside a string start a comment?

No. A # inside quotation marks is part of the string and is printed like any other character. The # starts a comment only when it appears outside a string.

Ready for the next step?Learn how to store and name data with variables.
Next: Variables & Naming Rules →