Python Multiline Comment – How to Add Comments to Your Code

How to create a python multiline comment – this is a common question, but it’s also kind of a trick question. Python doesn’t have a mechanism for adding multiline comments or ‘block comments’ to your code, though that doesn’t mean it’s not possible! Read on to find out how to do comments in python! But first..

So, what are Multiline Comments?

When writing code, it’s useful to be able to add comments – it makes it easier to understand for those that are reading or editing your code. You can enter a single line comment in python by using the hash character – #. For example:

# This prints Hello
print("Hello")

Now, many languages also allow for multiline comments. For example, you can create Powershell a multline comment like this:

<#
 this is a powershell multiline comment
 comment
 #>

Multiline Comments in Python

So, how do you do this in Python? Well…. you can’t! At least not exactly, however you have a couple of options, the first is to use multiple single line comments. For example:

#This prints
#Hello
print("hello")

This is nice and easy, though it does mean you need to remember to start each line as a comment. This is currently the only official way to create comment blocks in Python. There is another way however. Another option would be to create a multiline string to use as a comment. You can use triple-quoted strings. When they’re not a docstring (the first thing in a class/function/module), they are always ignored. For example, using the python print statement below:

"""
This is a multiline 'comment' 
in python. 
This script prints Hello
"""
print("hello")

Whilst this works, python will not identify this as a comment. It will be processed when your script runs, though it won’t actually do anything. Although this approach works, it’s not a great way around the problem of multiline comments in python. Personally, I always take the first option of using multiple single line comments! Hopefully this has better helped you understand how to make a python multiline comment!

Related posts

Mastering the Linux ifconfig Command

Docker Exec Command With Practical Examples

Debugging with Git Bisect

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More