Skip to content

Comments#

When we need to annotate or leave a note about what a piece of code does, we comment it. Comments are designed for other programmers to read. Python ignores them.

Comments are useful for when a piece of code isn't obvious, like a complex algorithm. They're also useful for some very powerful, advanced features like automatically generating documentation or tests. We won't cover that advanced use case.

Here's what a single line comment looks like in Python:

1
# I have a comment to make about this code

Anything after the # is ignored, but not before it, like this:

1
print("Hello, World!")  # This prints "Hello, World!" to the terminal

Adding comments to the end of code can make it harder to read, so I recommend keeping them on the line above. Let's refactor the above "code":

1
2
# This prints "Hello, World!" to the terminal
print("Hello, World!")

This is preferred.

Use comments to tell future you something about the code, or other developers, if you feel the code is complex enough to warrant it.

This is from our script:

1
2
# Imports the Python "sys" package
import sys

This comment is an example of when not to comment some code. It's not telling us something new or which we cannot work out ourselves.