Python Comments

Louis SanchezJanuary 20th 2021, 8:42

Comments are an integral part of programming.

There are three different ways to write Python comments, documentation strings (docstrings for short), inline comments, and block comments.

Block Comments

Step 1 : Block and inline comments start with a pound sign, #. A block comment comes in the line before the statement it annotates and is placed at the same indentation level:

# increment counter

counter = counter + 1

Inline Comments

Step 2 : Inline comments are placed on the same line as the statement it annotates:

print(foobar) # this will raise an error since foobar isn't defined

Documentation Strings

Step 3 : A documentation string, or docstring for short, is a literal string used as a Python comment. It is written and wrapped within triple quotation marks; """ or '''. Docstrings are often used to document modules, functions, and class definitions. The following is an example module that's been documented with a docstring. Module docstrings should be put at the beginning of the file:


This script can be called with two integer arguments to return their sum


import sys

num_1 = int(sys.argv[1])

num_2 = int(sys.argv[2])

print(num_1, "+", num_2, "=", num_1 + num_2)

Step 4 : you can also use docstrings to write multiline comments:


This loop goes through all the numbers from 1 to 100

printing each out


for i in range(1, 101):