Chapter 9. Just for You—Comments

 

Up until now, everything we have typed into our programs (and in interactive mode) has been instructions to the computer. But it’s a very good idea to include some notes to yourself in your programs, describing what the program does and how it works. This will help you (or someone else) look at your program later and figure out what you did.

In a computer program, these notes are called comments.

Adding comments

Comments are only for you to read, not for the computer to execute. Comments are part of the program’s documentation, and the computer ignores them when it runs your program.

Python has a couple of ways to add comments to your program.

Word Box

Documentation is information about a program that describes the program and how it works. Comments are one part of a program’s documentation, but there may be other parts, outside the code itself, that describe things like

  • why the program was written (its purpose)
  • who wrote it
  • who it’s meant for (its audience)
  • how it’s organized

and much more. Larger, more complicated programs usually have more documentation.

The Python help that we mentioned in “Thinking like a (Python) programmer” in chapter 6 is a kind of documentation. It’s meant to help users—like you—understand how Python works.

Single-line comments

You can make any line into a comment by starting it with the “#” character. (This is called the number sign or sometimes the pound sign.)

End-of-line comments

Multiline comments

Commenting style

Commenting out

What did you learn?

Test your knowledge

Try it out