Python Comments
A comment is text in a program that Python ignores. Comments are written for people: for the reader who wants to understand the code, and for you, a few weeks later, when you have forgotten why you wrote it that way. Good comments explain why something is done; the code itself already shows what is done.
Comments with the hash sign
A comment starts with # and goes to the end of the line. It can stand on its own line or after code:
# This program works out the area of a room.
length = 4.5 # metres
width = 3.2 # metres
area = length * width
print("Area:", area, "square metres")Area: 14.4 square metres
Python reads the first line, sees # and skips the rest of it. Everything before a # on a line still runs. A # inside a string is just a character, not a comment: print("#1 player") prints #1 player.
Comments over several lines
Python has no special symbol for a comment of several lines: you start each line with #. Most editors can add or remove the # signs for a selection of lines at once.
# The price includes tax.
# The tax rate is 18 percent,
# so the price without tax is price / 1.18.
price = 118
print(round(price / 1.18, 2))100.0
Docstrings
A string that stands alone as the first line of a function, a class or a file is called a docstring. It describes what the code does, and tools can show it as help. Docstrings are usually written with three quotes, which allow several lines:
def greet(name):
"""Return a friendly greeting for name."""
return "Hello, " + name + "!"
print(greet("Ravi"))
print(greet.__doc__)Hello, Ravi! Return a friendly greeting for name.
You will learn about functions later; for now, notice that the docstring is kept and can be read with __doc__.
Commenting out code
While testing, you can put # in front of a line to switch it off without deleting it. This is called commenting out. Remove the # to switch the line on again. Do not leave large blocks of commented-out code in a finished program, though: they confuse the next reader.
Practice exercises
- Add a comment above each line of one of your earlier programs, explaining what the line is for.
- Write a line of code with a comment after it on the same line.
- Comment out one
printline, run the program and check that it no longer prints. - Write a function with a docstring and print the docstring.