Python Comment With Examples

This article entitle Python Comment is a continuation of the previous article entitled Python Basic Syntax.

The Python Comment is used to make the code more readable, it can also be used for explaining lines of code, and also useful to understand the code, and it can be also used to prevent the execution when testing a piece of code.

What is Python Comments?

In Python, comment can be identified with a hash symbol ( # ) and can be used to extend the end of the line. Further, the hash characters cannot be considered comments.

The following list is 3 types of comments.

  • Single line Comments
  • Multiline Comments
  • Docstring Comments

Python Single Line Comments

The single-line comments can be created simply at the beginning of a line with a hash ( # ) symbol and automatically terminated at the end.

Example

# This is a single inline comment in python

print ("Hello, World!")

Python Multiline Comments

The /* is a block comment that supports for multi-line comments in python, most programming languages have built-in comments to explain and span multiple lines of code.

Example

/*
This is a comment block.
that spans multiple lines.
Nice, right?
*/

There is also another way to comment multiline by simply adding a hash ( # ) symbol in each line of code.

Example

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Python Docstring Comments

Docstring is a built-in feature in Python which used for commenting on methods, modules, objects, functions, and classes. They can be written in the very first line after a module is defined, method, function and etc.

With the use of triple quotes (‘’ or ““”) if you did not use it in the first line the Python interpreter will not identify it as a docstring or else you can access the docstring using a __doc__ attribute.

Example

def add(a, b):
    """Function to add the value of a and b"""
    return a+b

print(add.__doc__)

Output

Function to add the value of a and b

What is the shortcut for comment in Python?

The shortcut comment in Python is (CTRL-K, CTRL-C) and the shortcut for uncomment is (CTRL-K, CTRL-U).

How do you comment out an entire section in Python?

The most common way to add comments and comment out an entire section is using the hash ( # ) symbol. Any line of code which starts with s ( # ) has been served as a comment and the compiler ignores it.

Summary

In summary, you have read about Python Comment. We also discussed in this article what is Python comments, single-line comments, multi-line comments, and docstring comments, what is the shortcut for comment and how you comment out an entire section.

I hope this article about Comments could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment