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.
# Calculate the area of a rectangle
width = 8
height = 5
area = width * height # area = width x height
print("Area:", area)# tells Python to ignore the rest of the line. It is a note that explains the purpose of the program.width = 8 creates a variable named width and stores the number 8 in it.height = 5 creates a variable named height and stores the number 5 in it.width by height and stores the result, 40, in area. The text after # is an inline comment, separated from the code by two spaces as PEP 8 recommends. Python skips it.print() displays the label and the value of area, so the output is Area: 40.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.
# 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)#.price = 200 stores the number 200 in the variable price.tax_rate = 0.18 stores the decimal number 0.18, which means 18 percent.price * tax_rate first, which is 36.0, and then adds the price. The result, 236.0, is stored in total.print() displays Total: 236.0. The comment lines produce no output.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.
# 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")#, but because it is inside a string it is ordinary text. The # after the closing quote starts a real inline comment.print(message) displays Use # to start a comment. The hash symbol appears in the output because it was part of the string.#, Python treats the whole line as a comment. The print() call is disabled and nothing is displayed for it.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.
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__)def square(n): starts a function named square that takes one parameter, n. The colon introduces the indented body.square. It is written with triple double quotes and uses the imperative mood.return n * n sends the square of n back to the caller.square(6) returns 36, and print() displays it.square.__doc__ gives the docstring text, so the output is Return the square of a number. This is the same text that help(square) would display.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.
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))def bmi(weight, height): starts a function with two parameters. The docstring follows on the next line.Args: introduces a list of the parameters. This layout is a common convention. Python does not enforce it.weight is expected in kilograms.height is expected in metres.Returns: introduces a description of the value that the function gives back.round(..., 1) rounds the result to one decimal place.input() reads the first line of the Program Input box as text, and float() converts it to a decimal number. With the default input, weight is 70.0.height is 1.75.print() displays the result. For 70 kg and 1.75 m the output is BMI: 22.9.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.
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")class Greeter: starts a new class. Classes are explained in the object-oriented lessons.Greeter.def hello(self, name): defines a method inside the class. The first parameter, self, refers to the object itself.hello.Hello, followed by the name.__doc__ at the top level holds the module docstring, so this line prints Utility module for greeting people.Greeter.__doc__ prints A simple class that greets a person.Greeter.hello.__doc__ reaches the method through the class and prints its docstring.Greeter() creates an object, and .hello("Asha") calls the method, which prints 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.
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)TODO: reminds the programmer about work that is still to be done. Many editors highlight these markers.discount = 10 stores the discount. The inline comment tells the reader that the number is a percentage and that it is fixed for now.input() reads the first line of the Program Input box as text, and float() converts it to a decimal number. With the default input, price is 250.0.price * discount / 100, which is 25.0. Subtracting it from the price gives 225.0.# to print the value while testing. The text after the second # is a comment about the code.print() displays the final message. With the default input, the output is Price after discount: 225.0.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 python3on 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
# noqaor# type: ignoreare 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 aSyntaxErroror aNameError. - Unclosed triple quotes: a docstring that never closes causes a
SyntaxErrorsuch 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 beNone. - 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
iforforstatement, the indented lines below it cause anIndentationError.
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__, andhelp()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.