2.7: Formatting Code
- Page ID
- 117529
\( \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
- Identify good spacing for expressions and statements.
- Write multi-line statements using implicit line joining.
Recommended spacing
Most spaces in Python code are ignored when running programs; however, spaces at the start of a line are very important. The following two programs are equivalent:
- Good spacing:
name = input("Enter someone's name: ") place = input("Enter a famous place: ") print(name, "should visit", place + "!") - Poor spacing:
name=input ("Enter someone's name: " ) place =input("Enter a famous place: ") print( name,"should visit" , place+ "!")
One might argue that missing or extra spaces do not matter. After all, the two programs above run exactly the same way. However, the "poor spacing" version is more difficult to read. Code like name=input and place+ might lead to confusion.
Good programmers write code that is as easy to read as possible. That way, other programmers are more likely to understand the code. To encourage consistency, the Python community has a set of guidelines about where to put spaces and blank lines, what to name variables, how to break up long lines, and other important topics.
PEP 8 is the official style guide for Python. PEP stands for Python Enhancement Proposal. Members of the Python community write PEPs to document best practices and propose new features. The table below is based on guidelines from PEP 8 under the heading Whitespace in Expressions and Statements.
| Guideline | Example | Common Mistakes |
|---|---|---|
| Parentheses: no space before or after. |
|
|
| Commas: no space before, one space after. |
|
|
|
Assignment: one space before and after the |
|
|
|
Concatenation: one space before and after the |
|
|
| Arithmetic: use space to show lower precedence. |
|
|
Which statement is formatted properly?
name = input("What is your name? ")name = input ("What is your name? ")name = input( "What is your name? " )
- Answer
-
a. The code has one space before and after the assignment operator (=).
Which statement is formatted properly?
name=name+"!"name = name+"!"name = name + "!"
- Answer
-
c. Each operator (=, +) has one space both before and after.
Which statement is formatted properly?
print("Hello",name)print("Hello", name)print("Hello " , name)
- Answer
-
b. The comma is followed by a space.
Which expression is formatted properly?
b**2 - 4*a*cb ** 2 - 4 * a * cb**2 - 4*a * c
- Answer
-
a. The expressions
b**2and4*a*care evaluated first. Adding space around the-operator makes the order of operations more readable.
Automatic concatenation
Long strings make Python programs difficult to read. Ex: This program prints the first sentence of the US Declaration of Independence:
print("The unanimous Declaration of the thirteen united States of America, When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.")
PEP 8 recommends that each line of code be less than 80 characters long. That way, programmers won't need to scroll horizontally to read the code. The above program can be rewritten by breaking up the original string:
print("The unanimous Declaration of the thirteen united States of "
"America, When in the Course of human events, it becomes "
"necessary for one people to dissolve the political bands "
"which have connected them with another, and to assume among "
"the powers of the earth, the separate and equal station to "
"which the Laws of Nature and of Nature's God entitle them, a "
"decent respect to the opinions of mankind requires that they "
"should declare the causes which impel them to the separation.")
For convenience, Python automatically concatenates multiple strings. The + operator is not required in this situation.
Which line prints the word "grandmother"?
print(grandmother)print("grand" "mother")print("grand", "mother")
- Answer
-
b. The two consecutive strings are automatically combined into one string before printing.
What string is equivalent to "Today is" "a holiday"?
'Today isa holiday''Today is a holiday''Today is" "a holiday'
- Answer
-
a. The original strings do not have a space between the words
"is"and"a".
If name is "Ada", what does print("Hello," name) output?
Hello,AdaHello, AdaSyntaxError
- Answer
-
c. The literal
"Hello,"and the variablenamecannot be concatenated without using a+operator. Alternatively, the two values could be separated by a comma in the print function.
Multi-line statements
Most statements in a Python program need only one line of code. But occasionally longer statements need to span multiple lines. Python provides two ways to write multi-line statements:
- Explicit line joining, using
\characters:decl = "The unanimous Declaration of the thirteen united States of " \ "America, When in the Course of human events, it becomes " \ "necessary for one people to dissolve the political bands..." - Implicit line joining, using parentheses:
decl = ("The unanimous Declaration of the thirteen united States of " "America, When in the Course of human events, it becomes " "necessary for one people to dissolve the political bands...")
Implicit line joining is more common, since many statements and expressions use parentheses anyway. PEP 8 recommends avoiding the use of explicit line joining whenever possible.
Which character is used for explicit line joining?
/\|
- Answer
-
b. The backslash, when used at the end of a line, indicates a multi-line statement.
What is the best way to print a very long string?
- Break up the string into multiple smaller strings.
print("..." # first part of string "..." # next part of string "...") - Print the string using multiple print statements.
print("...") # first part of string print("...") # next part of string print("...") - Assign the string to a variable and print the variable.
text = "..." # the entire string print(text)
- Answer
-
a. Using one print statement with parentheses joins the lines implicitly and does not increase the number of statements.
Which example consists of two statements?
-
print("Happy " "New Year") -
saying = ("Happy " "New Year") -
saying= "Happy " "New Year"
- Answer
-
c. The first line assigns
"Happy "to the variable saying. The second line has no effect on the program.
The following code works correctly but is formatted poorly. In particular, the code does not include spaces recommended by PEP 8. Furthermore, two of the lines are about 90 characters long. Reformat the code to follow the guidelines in this section. Be careful not to change the behavior of the code itself.
Interactive Code
- Input
-
forgetful
magical
potato
reception
3
7
4 - Answer
-
adj1 = input("Adjective: ")
adj2 = input("Adjective: ")
noun1 = input("Noun: ")
noun2 = input("Noun: ")
x = int(input("Integer: "))
y = int(input("Integer: "))
z = int(input("Integer: "))
print()
print("A vacation is when you take a trip to some",
adj1, "place with your", adj2, "family.")
print("Usually you go to some place that is near a/an",
noun1, "or up on a/an", noun2 + ".")
print("To be worthwhile, you should travel at least",
x**3 + y**3 + z**3, "kilometers away.")
Write a program that prints the following five quotes (source: BrainyQuote) from Guido van Rossum, the creator of Python. Your program should have exactly five print statements, one for each quote:
1. "If you're talking about Java in particular, Python is about the best fit you can get amongst all the other languages. Yet the funny thing is, from a language point of view, JavaScript has a lot in common with Python, but it is sort of a restricted subset."
2. "The second stream of material that is going to come out of this project is a programming environment and a set of programming tools where we really want to focus again on the needs of the newbie. This environment is going to have to be extremely user-friendly."
3. "I have this hope that there is a better way. Higher-level tools that actually let you see the structure of the software more clearly will be of tremendous value."
4. "Now, it's my belief that Python is a lot easier than to teach to students programming and teach them C or C++ or Java at the same time because all the details of the languages are so much harder. Other scripting languages really don't work very well there either."
5. "I would guess that the decision to create a small special purpose language or use an existing general purpose language is one of the toughest decisions that anyone facing the need for a new language must make."
Notice that all of these lines are longer than 80 characters, and some contain single quote marks. Format the code using multi-line statements and escape sequences as necessary.
Interactive Code
- Answer
-
print('1. "If you\'re talking about Java in particular, Python is about the '
'best fit you can get amongst all the other languages. Yet the funny '
'thing is, from a language point of view, JavaScript has a lot in '
'common with Python, but it is sort of a restricted subset."')
print('2. "The second stream of material that is going to come out of this '
'project is a programming environment and a set of programming tools '
'where we really want to focus again on the needs of the newbie. This '
'environment is going to have to be extremely user-friendly."')
print('3. "I have this hope that there is a better way. Higher-level tools '
'that actually let you see the structure of the software more clearly '
'will be of tremendous value."')
print('4. "Now, it\'s my belief that Python is a lot easier than to teach to '
'students programming and teach them C or C++ or Java at the same time '
'because all the details of the languages are so much harder. Other '
'scripting languages really don\'t work very well there either."')
print('5. "I would guess that the decision to create a small special purpose '
'language or use an existing general purpose language is one of the '
'toughest decisions that anyone facing the need for a new language must '
'make."')


