How to Comment in Python

November 25, 2019

Updated in July 2021

Introduction

A key skill in writing code is the ability to use comments. Comments are lines that compilers and interpreters ignore that developers use to leave notes about the function of the code. Additionally, they can also be used to disable parts of the code.

This guide will show you how to use comments in Python effectively.

Tutorial on how to use comments in Python.

Prerequisites

  • A working Python programming environment
  • The ability to create and edit Python files

Python Comment Syntax

To add or mark a line as a comment, start with a hash sign (#) and a space:

# This is a sample comment.

Using the hash sign to start the line tells the system to ignore everything in that line. When the application runs, the program pretends like those lines don’t exist. However, you can still see it when you edit the file.

For example, in the Hello World program below:

# Display the text "Hello, World!" on the screen.
print("Hello, World!")
adding a comment to python script

The system runs the code print("Hello, World") in line four, whereas the line above it explains what the code is supposed to do.

You can set any line as a comment, and use as many as you like. If your code has different blocks, you can use a comment to explain each one. For example:

# Define a variable flowers as a list of strings.
flowers = [‘rose’, ‘carnation’, ‘daisy’, ‘marigold’, ‘tulip’, ‘sunflower’]

# Create a for loop to iterate through flowers list, and displays each string item.
for flower in flowers:
            print(flower)
how to add multiple comments in python

Python Comment Block

Block comments are longer-form comments that consist of multiple lines in a row. A developer uses them to explain more complex code, especially when working in a team.

To mark a series of lines as a comment, add a hash sign + space at the beginning of each line:

# This is a comment
# that runs on to
# multiple lines.

Some text or code editors for programming (like Notepad++ or Atom) allow you to highlight the text, then mouse-click to mark the block as a comment. These tools can save you time commenting out each line.

Python Multiline Comment

In general, it is recommended to use # at the beginning of each line to mark it as a comment. However, commenting a large section takes a lot of time and you may need a quick way to comment out a whole section. In such instances, you can use multi-line comments.

Multi-line strings do not work as traditional Python comments, since there is no official multi-line functionality. Instead, use multi-line strings wrapped inside triple-quote marks (""") to achieve a similar function.

For instance:

def addition_test(a, b):
    result = a + b
    """
    This is a block
    of commented lines.
    They aren’t parsed and interpreted by the compiler.
    """
return result
how to have multi-line comments in python

Note: It is important that you correctly indent the triple-quote mark. If you don’t, you will see a syntax error.

This method creates a text constant with no function, not a true comment. As long as you don’t add anything that accesses that string of text, it works the same as a regular comment.

The triple-quotation mark can be tricky because in some circumstances it creates a docstring if a triple-quote:

  • follows a function signature,
  • follows a class definition,
  • is at the start of a module.

If you place """ in one of the places listed above, Python reads it as a dosctring. Docstrings let you put human-readable text into the project. This is usually used to create documentation that’s part of the application and can be accessed at runtime.

Python Inline Comment

You can comment in the same line as a piece of code using an inline comment. The best time to use this option is when explaining a complicated operation.

Use an inline comment to point out the exact spot you want to clarify. Add the standard hash sign + space to signify an inline comment:

function
    set variable
    run command
    run additional command        # Tricky part:  The program breaks if this line is removed.

Inline comments are used to add context for people reading the code. For example, you might explain the purpose of a variable, or leave a note about the type of variable created. It can also be helpful to explain why a particular command is used, as in the example above.

comment on the same line as a piece of code

Python Comment Out

Because comments render text invisible to the parser, you can use them to disable commands. Doing so lets you test segments of code with and without new additions.

For example, in this simple dice rolling program, there is a section that’s commented out. If you remove the hash sign, you enable the code to test it.

import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
     print "Rolling the dice..."
     print "The values are...."
     print random.randint(min, max)
     print random.randint(min, max)

# Add two random numbers together for a sum
# while roll_again == “yes” or roll_again == “y”:
    # print ”Rolling the dice…”
    # print “You rolled a “
    # print random.randint(min,max) + random.randint(min, max)

    roll_again = raw_input("Roll the dice again?")

Why Are Comments Important In Python

Commenting can help you:

  • Understand your own code when you come back to it after a longer period of time.
  • Get you back up to speed faster.
  • Debug issues.
  • Understand certain code choices when working within a team.
  • Prevent potential issues by emphasizing why a specific code part is important.

Python Code Comments Best Practices

  • Comment at the same indentation as the code you’re referring to. This makes it easier to see what you’re referring to.
  • Update your comments when you update your code. Incorrect comments are worse than no comments.
  • Use complete sentences. Capitalize appropriate words, unless you’re referring to an identifier (like a variable). Never change the case of an identifier.
  • Block comments should be written out in complete sentences, with periods. Aim for 80 words per line or less.
  • If you have multiple sentences in a comment, use a double-space between sentences.
  • Write comments in English.
  • For a block comment with multiple paragraphs, add a blank line between paragraphs with a single comment tag preceding a blank line.
  • For inline comments, leave at least two spaces between the code and the comment. Use inline comments sparingly, and avoid using them to state the obvious.

AVOID:

  • Don't comment on code that is self explanatory. Stick to the principle of writing DRY (Don't Repeat Yourself) and avoid WET (Write Everything Twice) code and comments.
  • Avoid using comments to explain messy code - comments should support code not justify it.

Conclusion

You should now understand how (and why) to make comments in the Python language.

Was this article helpful?
YesNo
Sofija Simic
Sofija Simic is an aspiring Technical Writer at phoenixNAP. Alongside her educational background in teaching and writing, she has had a lifelong passion for information technology. She is committed to unscrambling confusing IT concepts and streamlining intricate software installations.
Next you should read
Install Python on CentOS 8
January 20, 2020

This tutorial provides instructions on installing Python 3 and Python 2 on CentOS 8 with guidance on how to...
Read more
How to Check Python Version in Linux, Mac, & Windows
October 1, 2019

Python is a popular programming language with different versions organized by release date...
Read more
How to Get the Current Date and Time in Python
August 14, 2019

The article shows you how to create a basic Python script that displays the current date and time...
Read more
How To Install Python 3 on Windows 10
April 2, 2019

Unlike most Linux distributions, Windows does not come with the Python programming language by default...
Read more
  • © 2021 Copyright phoenixNAP | Global IT Services. All Rights Reserved.