How to Write Comments in Python

Commenting in Python is a handy way to write notes about your code. These annotations can be for your future self or to help other programmers quickly get a grasp of what is happening in a program.

 

There are two ways to write comments in Python, which we will have a look at below.

 

Single-line Python Comments

To create a single-line comment in Python place a # (hash) at the beginning of the line you wish to comment-out.

 

# This is a comment.

 

If you have more you wish to say but don't want the comment to be one big line, keep adding new lines starting with a # (hash) - this is considered best practice.

 

# This is a comment.
# and some more info.
# and yet more info.

 

Multi-line Python Comments

There are some cases where you need to make a large commented-out section in your Python program. This might be when you don't want a section of code to run. Multi-line comments start with """ (three speech marks) and must be closed with """ (three more speech marks).

 

"""
if 2 > 1:
   print('This code is commented out in a mult-line comment block.')
"""
if 2 > 1:
   print('Code will contuine to run after closing the comment.')

 

Conclusion

You now know how to use comments in Python. In most cases, you will want to stick to single-line comments, for the purpose of annotating your program. With that said multi-line comments do have their uses when it comes to testing programs without certain blocks of code running.

comment