Skip to content

#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.

Single-line comments

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

# This is a comment
print("Hello world")

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

print("Hello world") # this is another comment

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:

1
2
3
4
# If you like typing many #,
# you can create a multi-line
# comment this way
print("Hello world")

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:

1
2
3
4
5
6
"""
This is 
a multi-line
comment
"""
print("Hello world")

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.