Comment in Python

When you are writing code, you are necessarily putting down your thoughts for the computer to read and execute. Nonetheless, there are instances where you may need to explain your opinions to yourself and others who may read your scripts. Commenting on codes will help you when you want to improve your script later after you have had more experience.

Comment in Python starts with a hashtag. Whenever you write a hashtag in your script and follow it by text, Python will ignore that text and not read it. You can even use the hashtag or comment tag if you want Python to ignore a block of code.

Single line comment

Now, this kind of comment is the most commonly used type. You write the hashtag and follow it with the comment you want to make or the code you want Python to ignore.

# this is a variable
learn = 14000

You can also write a single-line comment in front of a code you want to comment on instead of above it.

learn = 14000   # this is a variable

Multi-line comment

You can turn a block of code into a comment by highlighting the block and pressing CTRL/CMD + /. This will add a hashtag in front of all the lines in the code block.

# salary = 5300
# vacation = 2

# if salary > 500 and vacation > 2:
#     print ("I will take the job")
# else:
#     print ("This job is shit. I don't want it.")

All the lines are green now. The computer will neither read nor run the code this way, no matter how many times you run it.

Another cool way to create something that Python will ignore is by using multiline string tags. Remember the three quotation marks.

Logically, Python ignores any string that is not assigned to a variable:

"""
This is
a multiline comment
written in 3 lines
"""

If you run this, nothing will happen. Python did not read it.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials