Rocket opens a program he wrote last month and frowns at the screen. "I know I made this," he says slowly, "but I have no idea what the third part was supposed to do."
Raven reads over his shoulder, line by line, and taps her notebook. "What do you notice?" she asks. "You wrote notes for every experiment in here. Your program has no notes at all."
Nova blinks thoughtfully. "Interesting," she says. "Python can skip any line that starts with a hash mark. That means you can write notes that only people will read."
Rocket laughs and adds a short note above each part of the program. His future self will thank him.
A comment starts with the # sign. Python ignores everything from the # to the end of that line. Comments are for people: they explain what the program does and why.
Good programmers put a comment at the top of each file with its name and its job. They also add short comments above parts that are not obvious.
A comment can sit at the end of a line of code too. Python runs the code and skips the note after the #.
# launch_banner.py
# Shows a banner at the start of each session.
print("*" * 24)
print(" MISSION CONTROL") # the title line
# print("TEST LINE")
print("*" * 24) ************************
MISSION CONTROL
************************ Putting a # in front of a line of code is called commenting it out. The line stays in the file, but Python skips it. Programmers do this to switch a line off for a test without deleting it.
To switch the line back on, delete the # and save again.
| Line in a program | Does Python run it? |
|---|---|
| print("Ready") | ? |
| # print("Ready") | ? |
| print("Go") # start here | ? |
| # This program draws a banner. | ? |
There is one surprise. A # inside a string is just a character in the text. Only a # outside quote marks starts a comment.
# bay_sign.py
print("Docking Bay #4") # the sign on the door
# print("Closed for repairs")
print("Status:", "open") Docking Bay #4 Status: open
| Line | Is part of it a comment? |
|---|---|
| print("Room #2") | ? |
| print("Room 2") # second room | ? |
| # print("Room 3") | ? |
| print("#" * 5) | ? |
Comments make your programs easier to read, test and fix. Tomorrow you will meet error messages, and you will learn to read them like a detective reads clues.