Week 1 - Section 1 - Input and Output

Chapter 1.5 - Comments

Chapter 1.5 - Comments

Sometimes code needs some extra explanation to the person reading it. To do this, we add “comments” to the code. The comments are meant for the human reading the code, and not for the computer. 

There are two ways to create a comment. The first is to use the # symbol. The computer will ignore any text in a Python program that occurs after the #. For example:

# This is a comment, it begins with a # sign
# and the computer will ignore it.
print("This is not a comment, the computer will")
print("run this and print it out.")

If a program has the # sign between quotes it is not treated as a comment. A programmer can disable a line of code by putting a # sign in front of it. It is also possible to put a comment in at the end of a line.

print("A # sign between quotes is not a comment.")
# print("This is a comment, even if it is computer code.")
print("Hi") # This is an end-of-line comment

It is possible to comment out multiple lines of code using three single quotes in a row to delimit the comments.

print("Hi")

'''
This is
a
multi
line
comment. Nothing
Will run in between these quotes.
print("There")
'''
print("Done")

Most professional Python programmers will only use this type of multi-line comment for something called docstrings. Docstrings allow documentation to be written along side the code and later be automatically pulled out into printed documentation, websites, and Integrated Development Environments (IDEs). For general comments, the # tag works best.

Even if you are going to be the only one reading the code that you write, comments can help save time. Adding a comment that says “Handle alien bombs” will allow you to quickly remember what that section of code does without having to read and decipher it.