Skip to main content

Foundations of Python Programming: Functions First

Section 1.10 Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments.
A comment in a computer program is text that is intended only for the human reader - it is completely ignored by the interpreter. In Python, the # token starts a comment. The rest of the line is ignored. Here is a new version of Hello, World!.
Notice that when you run this program, it still only prints the phrase Hello, World! None of the comments appear. You’ll also notice that we’ve left a blank line in the program. Blank lines are also ignored by the interpreter, but comments and blank lines can make your programs much easier for humans to parse. Use them liberally!
Another way to use comments is to use them to plan your program - by including the natural language or pseudocode version of the algorithm an outline before you start coding. Consider how the code below uses comment to indicate the steps one might use to solve a word problem:
#1 set all known values and constants

#2 formulae (coded as functions)
## unit conversions

## governing equations

#3 user input

## convert units

#4 solving 


#5 rounding for significant digits

#6 solutions statement to display the answer
There is one other way in Python that code is sometimes documented, by enclosing portions of the text within triple-quotes, """ """. This tells Python that the text should be treated as a string instead of as code to interpret. Strictly speaking, triple-quotes are not comments because the interpreter can still access their contents. In a later chapter we will discuss how this is useful when we document portions of our code (functions) with (docstrings). Some programmers take advantage of triple-quoted code not being executed as part of their debugging process: one can essentially ’turn off’ portions of our code without having to delete it, and then turn it ’back on’ by removing the enclosing triple-quotes.
Check your understanding

Checkpoint 1.10.1.

    What are comments for?
  • To tell the computer what you mean in your program.
  • Comments are ignored by the computer.
  • For the people who are reading your code to know, in natural language, what the program is doing.
  • The computer ignores comments. It’s for the humans that will “consume” your program.
  • Nothing, they are extraneous information that is not needed.
  • Comments can provide much needed information for anyone reading the program.
  • Nothing in a short program. They are only needed for really large programs.
  • Even small programs benefit from comments.
You have attempted of activities on this page.