1.7: Comments
- Page ID
- 117519
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Write concise, meaningful comments that explain intended functionality of the code.
- Write a docstring (more verbose comment) that describes the program functionality.
The hash character
Comments are short phrases that explain what the code is doing. Ex: Lines 1, 8, and 10 in the following program contain comments. Each comment begins with a hash character (#). All text from the hash character to the end of the line is ignored when running the program. In contrast, hash characters inside of strings are treated as regular text. Ex: The string "Item #1: " does not contain a comment.
When writing comments:
- The
#character should be followed by a single space. Ex:# End of menuis easier to read than#End of menu. - Comments should explain the purpose of the code, not just repeat the code itself. Ex:
# Get the user's preferencesis more descriptive than# Input item1 and item2.
|
1
|
# Display the menu options
print("Lunch Menu")
print("----------")
print("Burrito")
print("Enchilada")
print("Taco")
print("Salad")
print() # End of menu
# Get the user's preferences
item1 = input("Item #1: ")
item2 = input("Item #2: ")
The main purpose of writing comments is to _____.
- avoid writing syntax errors
- explain what the code does
- make the code run faster
- Answer
-
b. Comments help explain the purpose of code so that other programmers understand what the code intends.
Which symbol is used for comments in Python?
- #
- /*
- //
- Answer
-
a. The hash character indicates the beginning of a comment.
Which comment is formatted correctly?
- 0 spaces:
#Get the user input - 1 space:
# Get the user input - 2 spaces:
# Get the user input
- Answer
-
b. Having one space after the # is the community standard.
Code quality
The example program above had two parts: (1) display the menu options, and (2) get the user's preferences. Together, the blank lines and comments show the overall structure of the program.
Programmers spend more time reading code than writing code. Therefore, making code easier for others to read and understand is important. Two ways to improve code quality include:
- Separate each part (lines that have a similar purpose) with a blank line.
- Write a comment before each part. Not every line needs a comment.
Which comment is most useful for the following code?
print("You said:", adj1 + " " + noun1)
# Append adj1 and noun1# Print out a bunch of stuff# Show the resulting phrase
- Answer
-
c. This comment explains the intent of the code. If the code had a mistake, the programmer reading the comment might notice the mistake more easily.
Where should a blank line be inserted?
|
1
|
name = input("Whose birthday is today? ") |
|
2
|
print("Happy birthday to", name) |
|
3
|
print("Everyone cheer for", name) |
- After line 1
- After line 2
- After line 3
- Answer
-
a. A blank line separates the input from the output. Then again, inserting a blank line in a three-line program is generally unnecessary.
To temporarily prevent a line from being run, one might . . .
- introduce a syntax error in the line.
- remove the line from the program.
- insert a # at the beginning of the line.
- Answer
-
c. The # symbol "comments out" the line without removing the line permanently.
Documentation
Python programs may optionally begin with a string known as a docstring. A docstring is documentation written for others who will use the program but not necessarily read the source code. Most of the official documentation at docs.python.org is generated from docstrings.
Documentation can be long, so docstrings are generally written as multi-line strings ("""). Common elements of a docstring include a one-line summary, a blank line, and a longer description.
The main purpose of writing docstrings is to . . .
- summarize the program's purpose or usage.
- explain how each part of the code works.
- maintain a list of ideas for new features.
- Answer
-
a. The docstring is primarily written for others who will use the program.
Which of the following is NOT a docstring?
-
"""Vacations Madlib.""" -
"""Vacations Madlib. This program asks the user for two adjectives and two nouns, which are then used to print a funny story about a vacation. """ -
# Vacations Madlib. # # This program asks the user for two adjectives # and two nouns, which are then used to print # a funny story about a vacation.
- Answer
-
c. Docstrings must be a valid string, not a multi-line comment. Docstrings are stored in the program's memory, but comments are ignored.
Which docstring is most useful for this program?
-
"""Vacations Madlib.""" -
"""Vacations Madlib. This program asks the user for two adjectives and two nouns, which are then used to print a funny story about a vacation. """ -
"""Vacations Madlib. This program asks the user for two adjectives and two nouns, which are then used to print a funny story about a vacation. The code uses four variables to store the user input: two for the adjectives, and two for the nouns. The output is displayed on seven lines, beginning with a blank line after the input. """
- Answer
-
b. The amount of information in this docstring is just right. In most cases, the docstring should not be longer than the code.
Add two comments to the following program: one for the input, and one for the output. Separate the input and output with a blank line. Then, compare your comments with the sample solution, and ask yourself the following questions:
- Are your comments longer or shorter? Why?
- Is the formatting of your comments correct?
Interactive Code
- Answer
-
# Get the person's name
name = input("Whose birthday is today? ")
name = name + "!"# Print a birthday message
print()
print("Happy birthday to", name)
print("Everyone cheer for", name)
Write a docstring for the following program. The first line of the docstring should explain, in one short sentence, what the program is. The second line of the docstring should be blank. The third and subsequent lines should include a longer explanation of what the program does. At the end of the docstring, add a line that says "Author: " followed by your name.
Interactive Code
- Answer
-
"""Gravity calculation.This program asks the user for their name, says hello, and repeats
back their name followed by an exclamation point. Then the program
calculates the force of gravity on a 70-kg person on planet earth.Author: Katherine Johnson
"""name = input("What is your name? ")
print("Hello,", name + "!")# mass of the planet earth
m1 = 5.98e24
# mass of a person (in kg)
m2 = 70
# distance from earth's center
r = 6.38e6# gravitational constant
G = 6.674e-11
# Newton's law of universal gravitation
F = G * (m1 * m2) / r**2print("The force of gravity is", F, "Newtons")


