How to Comment in Python?

In this post, I'll show you how to comment on your code and give you some code examples of doing so.

How to Comment in Python?
Photo by Nubelson Fernandes / Unsplash

Commenting in Python is done using the # sign at the beginning of the comment. Keep reading for code examples.

Watch a video tutorial on my YouTube channel:

Oren's Coding YouTube Channel

You could comment at the beginning of a line like so:

# This class is very simple.

class Simple:
	...

You could also comment at the end of a code line:

def my_func(self):  # This method is not part of a class, so shouldn't have self.
	...

What about function documentation? Here's how you can do that.

def my_func():
	"""This function has a specific role.""""
    ...
    

How to Comment Out Python Code?

To comment out a line of code, add a hashtag sign at the beginning of the line to comment out that line of code.

# def my_func():
#    ...


If you're using visual studio code, you could highlight multiple lines of code and use CMD + dot(.) (or CTRL + dot(.) on Windows) to comment out all of those highlighted lines.  

Don't Comment Too Much

Commenting in Python is useful. But I've seen what happens when you abuse it. It would be best to have a super organized readme with everything you want to say about functions instead of many in-code comments.

I use comments to explain a piece of code that isn't intuitive to the flow of the program. High-quality code should explain itself by clearly breaking functions into pieces of logic and good naming conventions.

So, whenever you comment a lot on a 5-line function, ask yourself: should I write this elsewhere? How can I make the function more readable for other engineers?

Conclusion

In this article, I showed you how to comment using the # sign and gave some code examples. I also showed you how to document functions using the """ string at the top of a function.

If you want to learn more about comments in Python, you can check out the official documentation here.

Learning to document your code can be a serious advantage over other developers who don't bother. A good reason for you to learn to comment and document your code is to participate in open-source projects. If you want other people to use your work, they need to be able to understand it without too much fuss.

Check out other Python tutorials right here.