logo

How to write Comments in Python (Guide)

Comments can be added to Python programs, this makes your code easy to understand by others. A comment is human readable text that is not executed by Python.

It increases the readability of your code, comments are written for software developers. Comments are ignored by the Python interpreter

Python has several possibilities to add comments.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Python commenting

A single line comment can be added by using the hash (#) character. The hash (#) is added for every line that should be commented.

You can put any comment in the code:

# Show the world a message
print('Hello World')

If you use a modern Python IDE, it will highlight your comment in another color. Each comment is ignored by Python.

If a statement is put before the comment, the statement is run but the comment is ignored.

print("Run this")  # Ignore this

The code above will only show “Run this” in the terminal.

Python Mutliline Comments

Python does not have a way to add multiline comments with special characters.
A language like Java or C++ allows you to write multiline comments like this:

/* You can write
multiline comments
like this in C++ */

Then the whole block is ignored, but Python doesn’t have native multiline commenting support.

In Python you can create multiline comments like this:

# You can write
# multiline comments
# like this in Python

Another way to do this is using triple quotes ‘’’ characters, this is ignored by Python but officially that’s for documentation not comments.

'''
We can type multiple lines of commment
if we use the indicator.
'''

Why comments?

There are two main reasons to add comments to your code.

1) to make your own code more readable
2) to make your code understandable for others

Sometimes developers add notes or todo lists in their code.

As a developer you write a lot of code, and you may forget what a piece of code does. Commenting helps you increase your productivity.

Related Course: Python Programming Bootcamp: Go from zero to hero

Next

Leave a Reply

Login disabled