Block Comments in Python

Python | Block Comments: In this tutorial, we are going to learn about the block comments, inline comments, why and how to use them?
Submitted by Muskan Arora, on June 12, 2020

Comments

A comment is a piece of text in a computer program that is meant to be a programmer-readable explanation or annotation in the source code and is ignored by compiler/interpreter.

In simpler words, as we start adding more functionality and features to our program the size of code increases! It might happen that when we return to it after a few months we might not be able to understand it and get confused!

Thus adding comments in the program is one of the most important hygiene factors. It is important to make sure that your code can be easily understood by others and you (even when you revisit after a few months). Often text editors highlight comments differently so they can be easily identified.

Usually, the code only tells you how it does but cannot tell you why it does so?

Sometimes our variables are also not named very specifically. However, comments in Python can help us get better clarity. We use comments to explain the formulas and the actual logic behind the particular step/algorithm.

Type of Python Comments

Python can have both Block Comments and Inline Comments,

1) Block Comments

Block comments apply to the piece of code that it follows. It might apply to a portion of code or the entire code. They are indented to the same level as that code. Each line of comment starts with a #.

# Python program to print
# Hello World

print("Hello World")

Output:

Hello World

Block comments can also be made using ''' '''.  Anything written between these quotes is considered as comment.

'''
Python program to print
Hello World
'''

print("Hello World")

Output:

Hello World

Unless it is used right after the definition of a function, method, class, or module. In this case, it becomes a docstring.

def hello():
    '''
    Here, this is docstring 
    since it is written right after 
    the function definition.

    below given print statement will print 
    Hello World
    '''
    print("Hello World")

if __name__ == "__main__":
  # calling hello function
  hello()

Output:

Hello World

2) Inline Comments

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.

print("Hello World")  # This is an inline comment

Output:

Hello World

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.