Single, Multiline, Docstring Comments in Python

If you are interested to learn about the Python Applications

Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Comments enhance the readability of the code and help the programmers to understand the code very carefully. Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them

Example

#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Example

print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:

Example

#print("Hello, World!")
print("Cheers, Mate!")

Types of comments

 There are three types of comments in Python – 

  • Single line Comments
  • Multiline Comments
  • Docstring Comments

Single-Line Comments

Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:

Example: 

  • Python3
# Print “futurefundamentals!” to consoleprint("futurefundamentals")

Output

futurefundamentals

Multi Line Comments

Python does not really have a syntax for multi line comments. Python does not provide the option for multiline comments. However, there are different ways through which we can write multiline comments.

Using Multiple Hashtags (#)

We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered as a single-line comment. To add a multiline comment you could insert a # for each line:

Example

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:

Example

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Using String Literals

Python ignores the string literals that are not assigned to a variable so we can use these string literals as a comment

Example 1:

  • Python3
'This will be ignored by Python'

On executing the above code we can see that there will not be any output so we use the strings with triple quotes(“””) as multiline comments.

Example 2: Multiline comments using string literals

  • Python3
""" Python program to demonstratemultiline comments"""print("Multiline comments")

Output

Multiline comments

Python Docstring

Python docstring is the string literals with triple quotes that are appeared right after the function.It is used to associate documentation that has been written with Python modules, functions, classes, and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute.

Example:

  • Python3
def multiply(a, b):"""Multiplies the value of a and b"""return a*b  # Print the docstring of multiply functionprint(multiply.__doc__)

Output: 

Multiplies the va

Advantages of Using Comments

Using comments in programs makes our code more understandable. It makes the program more readable which helps us remember why certain blocks of code were written. Other than that, comments can also be used to ignore some code while testing other blocks of code. This offers a simple way to prevent the execution of some lines or write a quick pseudo-code for the program.

Block Comments

Block comments can be used to explain more complicated code or code that you don’t expect the reader to be familiar with. These longer-form comments apply to some or all of the code that follows, and are also indented at the same level as the code. In block comments, each line begins with the hash mark and a single space. If you need to use more than one paragraph, they should be separated by a line that contains a single hash mark. Here is an example of a block comment that defines what is happening in the main() function defined in the following:

# The main function will parse arguments via the parser variable.  These
# arguments will be defined by the user on the console.  This will pass
# the word argument the user wants to parse along with the filename the
# user wants to use, and also provide help text if the user does not
# correctly pass the arguments.

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "word",
      help="the word to be searched for in the text file."
  )
  parser.add_argument(
      "filename",
      help="the path to the text file to be searched through"
  )
...

Block comments are typically used when operations are less understandable and are therefore demanding of a thorough explanation. You should try to avoid over-commenting the code and should tend to trust other programmers to understand Python unless you are writing for a particular audience.

Inline Comments

Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin with a hash mark and a single whitespace character. Generally, inline comments look like this:

[code]  # Inline comment about the code

Inline comments should be used sparingly, but can be effective for explaining tricky or complex parts of code. They can also be useful if you think you may not remember a line of the code you are writing in the future, or if you are collaborating with someone who you know may not be familiar with all aspects of the code.

For example, if you don’t use a lot of math in your Python programs, you or your collaborators may not know that the following creates a complex number, so you may want to include an inline comment about that:

z = 2.5 + 3j  # Create a complex number

Inline comments can also be used to explain the reason behind doing something, or some extra information, as in:

x = 8  # Initialize x with an arbitrary number

Comments that are made in line should be used only when necessary and when they can provide helpful guidance for the person reading the program.

Commenting Out Code for Testing

In addition to using comments as a way to document code, the hash mark can also be used to comment out code that you don’t want to execute while you are testing or debugging a program you are currently creating. That is, when you experience errors after implementing new lines of code, you may want to comment a few of them out to see if you can troubleshoot the precise issue.

Using the hash mark can also allow you to try alternatives while you’re determining how to set up your code. For example, you may be deciding between using a while loop or a for loop in a Python game, and can comment out one or the other while testing and determining which one may be best:guess.py

import random

number = random.randint(1, 25)

# number_of_guesses = 0

for i in range(5):
# while number_of_guesses < 5:
    print('Guess a number between 1 and 25:')
    guess = input()
    guess = int(guess)

    # number_of_guesses = number_of_guesses + 1

    if guess < number:
        print('Your guess is too low')

    if guess > number:
        print('Your guess is too high')

    if guess == number:
        break

if guess == number:
    print('You guessed the number!')

else:
    print('You did not guess the number. The number was ' + str(number))

Commenting out code with the hash mark can allow you to try out different programming methods as well as help you find the source of an error through systematically commenting out and running parts of a program.

Single, Multiline, Docstring Comments in Python
Show Buttons
Hide Buttons