How to write comments in python?


Importance of comments in python programming

Why we have to write comments in Python? Good coders always make the best use of comment features while coding. Including comments in a code is a good habit. It helps in explaining the line of code to self and others. It is more helpful when we revisit our code after a long time back. When we forget everything about every line of code in the program, comments will be very helpful. Moreover, when we share our program with other developers, we need not have to explain the flow of the program. Comments included in the program helps in explaining the program. 

To understand deeper the comments in the program; It is basically to help the coder about the flow of a program. Python interpreter won’t interpret the comments as a part of the program.

Conversely, the multi-line comments included inside the function are considered as a documentation string to explain the working of that particular function or method. Therefore, in such cases, multi-line comments written as a documentation string can be printed out as an output if the programmer wants. This can be explained briefly later.

Now, let’s look into how to write the comments in a program. There are four ways:

  1. Block comment
  2. Inline comment
  3. Multiline Comment
  4. Documentation string


1. Block comment

Block comments generally apply to some (or all) code that follows them and are indented to the same level as that code. Each line of a block comment starts with a # and a single space.

Example:

# Hello world program
print("Hello world!")



2. Inline comment

An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are sometimes unnecessary and in fact distracting. Therefore, use inline comments sparingly.

Example:

print("Hello world!")  # Printing hello world


3. Multi-line Comment

Multi-line comments are stated within triple quotes, not within string literals. Python interpreter ignores them and it won’t be printed in the output result. You can use either single triple quotes (‘’’) or double triple quotes(“ ” ”), python interpreter treats the same. For one-liner multi-line comments, please keep the closing ” ” ” on the same line.

Example:

"""This is a multi-line comment
Python interpreter skips it
Use either double or single triple quote
"""
print("Coding is fun!")  

Output:

Coding is fun!

In the above example, you could see that text inside the triple quote is not executed by the interpreter. This is how we write multi-line comments in python. You can also use the multi-line comment technique to comment out a block of code when not necessary to execute.



4. Documentation string

Exceptionally, there is the so-called docstring (documentation string) which is a multi-line comment that can be printed as output. It’s an optional first statement of the function body which is written inside a triple quote and it can be printed on the output screen with a special method called __doc__. Docstring explains to the public the modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

Example:

def cal(a, b):
    """ This is a documentation string about function cal.
This functions does simple arithmetic calculation
"""
    sum = a + b
    product = a * b
    div = a / b
    sub = a - b
    return sum, product, div, sub
s, p, d, s = cal(20, 5)
print(f"Sum: {s}, Product:{p}, Division:{d}, Subtraction:{s}")
print(cal.__doc__) 

Output:

Sum: 15, Product:100, Division:4.0, Subtraction:15
 This is a documentation string about function cal.
This functions does simple arithmetic calculation

In the above example, a multi-line comment written inside the function is printed as an output with __doc__method. 



Comment conventions in Python

These conventions are based on PEP 8 of python. PEP 8 is a Style Guide for Python Code. All of the following points regarding writing comments are from python official documentation.

  1. Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
  2. Comments should be complete sentences. The first word should be capitalized unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
  3. Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.
  4. You should use two spaces after a sentence-ending period in multi-sentence comments, except after the final sentence.
  5. Ensure that your comments are clear and easily understandable to other speakers of the language you are writing in.
  6. Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don’t speak your language.
Summary
  • Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
  • Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does.
  • Block comment is more preferred than inline comments.

The basic syntax you have to know in Python