Python Friday #13: Add Comments to Your Code

While we should try to make our code as understandable as possible, sometimes we need to add comments. In this post I show you your options to add a comment to your Python code.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Single-line comments

We can create a comment in Python using the # character. Everything that comes behind it is a comment:

It does not matter if we write our comments on a new line or after our code. It works in both ways:

 

Multi-line comments

Some problems are more complex than others and require more words to explain them thoroughly. While we can repeat the single-line comments to get more lines, it is not a good approach:

While this works, it will be a pain to add more details later. You quickly will end up reformatting your comment and fight with the # at the start of the line. A much better way is to use a multi-line string that you do not assign to a variable:

If you need multi-line comments, use this approach. It has the same effect, but without the hassle of the other approach.

 

Conclusion

Adding comments to your Python code is easy. Try not to overuse them and think of other ways to write your code that not require a comment. And please, remove your no longer needed code and do not just add a # in front of it. You will thank me later.

1 thought on “Python Friday #13: Add Comments to Your Code”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.