By Developers, For Developers

Historical errata for Practical Programming

PDF PgPaper PgTypeDescriptionFixed onComments
71TYPO

>>> len(‘\\’) (first example of escaping) is syntactically incorrect. Was probably supposed to be in double quotes.

2013-03-05
13TYPO

1.2
‘Directions to the nearest bus station can be given in in English’ should be
‘Directions to the nearest bus station can be given in English’

1.3
‘Pretty much everyone has had a program crash. A standard story is that you were were typing’ should be
‘Pretty much everyone has had a program crash. A standard story is that you were typing’

2013-03-05
6TYPO

The web address in the installation instructions points to prag-prog.com instead of pragprog.com, i.e. there is an extra hyphen.
Also this hyperlink points to the 1st Edition instead of this edition.

2013-03-06
6SUGGEST

>>>As a real-life example of this kind of bug, the calendar program that one of the authors uses has a friend who was born in 1978. <<<

The calendar program has a friend?

2013-03-06I wish there was an upvote button. Nice find. :-)
92TYPO

‘Return True iff x is positive.’, it should be
‘Return True if x is positive.’

2013-03-19
109TYPO

>>> type(math)
<type ‘module’>

but I type that shell on my computers, it should be as follows.
>>> import math
>>> type(math)
<class ‘module’>

2013-03-19
2213SUGGEST

Second version.
Thank you for the quality of your cours in Cousera.
Excuse my english it is not my mother tong.

I want to add some explanation to get a better understanding
about the relation // and % in the page 13, starting at
"Be careful about using % and // with negative operands.

My suggestion:
Be careful about using % and // with negative operands. It
could look more natural to think about this functions like
this:

DividendDivisorQuotient_Remainder
_ 17 10_ 1_ 7
–17–10 1_–7
_ 17–10–1 7
–17_ 10–1–7

Freepascal and Delphi work like this. But this cause a lot
of bug. Example:

If you have a clock at 9.00h, what is the time 24 hours
before?

The answer is: –15 % 12
With Freepascal and Delphi you will get 2.00h, and it is
wrong.

To solve this kind of bug, the majority of the programming
language like Python use an other interpretation of //
and %:

DividendDivisorQuotient__Remainder
_ 17 10 1_ 7
–17–10_ 1_–7
_ 17–10–2_–3
–17_ 10–2_ 3

_ 17 17 1_ 0
–17–17_ 1_ 0
_ 17–17–1_ 0
–17_ 17–1_ 0

And with Python you will get the good answer:
–15 % 12 is equal to 9

What is important to remember:

—Python takes the floor of the result of an integer
division, the result is one smaller in negative answer
then positive answer:
>>> –17 // 10
–2

—Exception if your remainder is 0, the result is not
one smaller in negative answer but it still negative:
>>> 17 // –17
–1

—When using modulo,the sign of the result matches the
sign of the divisor (The second operand):
>>> –17 % 10
__3
>>> 17 % –10
–3

Remark:
Both interpretation of // and % work with the relation:
(b *(a // b) + a % b) is equal to a

My referance is: fr.wikipedia.org/wiki/Modulo_(op%C3%A9ration)

Thank you, Michel Lemay.

PS: The line in the tables and other places is only to get the
good position.

2013-07-08Thanks for the feedback! I'm glad you enjoyed the Coursera course!
146TYPO

‘In the code that follows, a list is created andstored in a variable;’ should be
‘In the code that follows, a list is created and stored in a variable;’

2013-03-19
169TYPO

‘but but this one uses break to terminate execution of the loop’ should be
‘but this one uses break to terminate execution of the loop’

2013-03-19
123TYPO

Here’s a piture of what happens when we do this

This should be “picture”.

2013-03-19
127TYPO

>>>9. Variables season refers to ‘summer’. Using string method format and the variable season, write an expression that produces ‘I love summer!’

Should be ‘variable’, singular.

2013-03-19
127TYPO

>>>10. Variables side1, side2 and side3 refer to 3, 4, and 5, respectively. Using string method format and those three variables, write an expression that produces ‘The sides have lengths 2, 3, and 4.’

The variables don’t match the output expected.

2013-03-19
203TYPO

‘After we do this analysis, we will see that we can can search a sorted list’ should be
‘After we do this analysis, we will see that we can search a sorted list’

2013-03-19
208TYPO

‘some some programmers dislike returning in the
middle of a loop’ should be
‘some programmers dislike returning in the
middle of a loop’

2013-03-19
136TYPO

>>> A lists has a type, and Python complains if you use a value of some type in an inappropriate way.

lists -> list, singular

2013-03-19
139TYPO

>>> In the code that follows, a list is created andstored in a variable

andstored -> and stored, need space

2013-03-19
140SUGGEST

Do the list methods clear() and copy() exsist?

2013-03-19
72TYPO

7. Following the Function Design Recipe, define a function that has four
parameters, grades between 0 and 100 inclusive, and returns the average
of the best 3 of those grades. Hint: call the function that you defined in
the previous questoin SPELLING

2013-03-19
72ERROR

question 10 - weeks_elapsed(20,3) - wouldn’t day1 be before day2 thus making the 3 refer to day 3 of the following year and the expected result being 49 not 2?

2013-05-16
111ERROR

The code for baking.py runs fine, but fails doctest because you use “return” for the results rather than “print.” As a result the test program produces the example between quotation marks, and therefore does not match the example you give. This may be an error in doctest rather than in the actual code. I just wanted to point out that the test fails.

2013-03-23
129TYPO

in method swapcase: charaters

2013-03-23
166TYPO

Rogue sentence in paragraph describing ‘while’ loop:

If that expression is false, Python skips the it evaluates the expression.

2013-03-24
194TYPO

Black text of question 10 has a word missing and (probably) a mis-spelling of dictionaries.

2013-04-17
233TYPO

Chapter 9 title is “Desiging Algorithms” instead of “Designing Algorithms”

2013-04-17
182TYPO

Second paragraph of text: “…Python has a for loop that lets YOUR process each element…”

Should be YOU

2013-04-17
201TYPO

Chapter title is misspelled.

Desiging Algorithms
in stead of
Designing Algorithms

2013-04-17
78TYPO

Right at the bottom of the page: output of running this program

and is in bold and purple

when it shouldn’t because it is inside the string which is being printed.

2013-05-16
154TYPO

Under Processing Parallel Lists Using indices:

Original:
Sometimes the data from one list correponds to data from another.

Should be:
Sometimes the data from one list corresponds to data from another.

2013-04-17
168TYPO

After the definition of remove_neg(num_list) Fuction

Original:
“When remove_negs([1, 2, 3, –3, 6, –1, –3, 1]) is executed,”

Should be:
“When remove_neg([1, 2, 3, –3, 6, –1, –3, 1]) is executed,”

2013-04-17
4739TYPO

4th para - The function body is indented. Here, we inded - should be .. we indent

2013-04-17
290TYPO

Unit test example. Chapter 15
Doc string from previous example
​class​ TestRunningSum(unittest.TestCase):
​“”“Tests for temperature.above_freezing.”“”

2013-04-17
260TYPO

make sure you test all all of them

you have 2 “all” words.

2013-04-17
76TYPO

If you are expecting the user to enter a number, you must use function int or float to convert get an integer or floating-point representation of the string:
‘convert get an integer’ it is convert or get, not convert get, one or the other not both.

2013-04-17
83TYPO

Similarly, evaluation of b2 and not b1 will produce True if b2 is True and b1is False.

should have a space after last b1

2013-04-17
64OK

The function call should be:
round(max(5.572, 3.258), abs(–2)))
the last parenthesis is missing

2013-04-17The function call parses fine as-is. Your suggestion gives the following error: \n \n>>> round(max(5.572, 3.258), abs(-2))) \n File "", line 1 \n round(max(5.572, 3.258), abs(-2))) \n ^ \nSyntaxError: invalid syntax \n \n...unless I'm missing something?
249SUGGEST

It may be nitpicking, but in talking about test cases you write “There are millions of numbers to choose from…” and (two paragraphs later) “We chose that value from among the billions of…” Which is it? Or is it that one could chose from an infinite number of values?

2013-05-16
156OK

table doesn’t print correctly need to add a print() after the ‘for j in numbers:’ loop ends.

def print_table(n):
“”" (int) -> None
Print the multiplication table for numbers 1 through n inclusive.
>>> print_table(5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
“”"
# The numbers to include in the table.
numbers = list(range(1, n + 1))

# Print the header row.
for i in numbers:
print(‘\\t’ + str(i), end=’’)

# End the header row.
print()

# Print each row number and the contents of each row.
for i in numbers:
print (i, end=’‘)
for j in numbers:
print(’\\t’ + str(i * j), end=’‘)
print(’’) # Added this for newline*

# End the current row.
print()

2013-04-17The code included with the downloads prints the table fine as-is (loop/multiplication_table.py). In the code you posted, the last two lines aren't indented far enough. Maybe it was a copy/paste error?
262TYPO

Hi

I think that when you define the repr method for atoms , the return statement should be

return ‘Atom({0}, “{1}”, {2}, {3}, {4})’.format(
self.number, self.symbol,
self.center[0], self.center[1], self.center[2])

and not

return ‘({0}, “{1}”, {2}, {3}, {4})’.format(
self.number, self.symbol,
self.center[0], self.center[1], self.center[2])

Thank you

2013-05-16
204OK

“a for loop over the indices” seems to be repeated. 2nd paragraph, 2nd sentence.

2013-05-16The phrases are slightly different: "a for loop over the **values**, a for loop over the **indices**".
36ERROR

braket for conversion to celsius in the programme is in wrong position giving wrong answer!7.12… mins instead of 7.8… mins. The statement at the top of the page 5/9*f - 32 is also wrong. Should be 5/9*(f-32)

2013-05-16
14TYPO

In section “1.2 What’s a Programming Language?”, the language is Portuguese, not Portugese.

2013-05-16
14TYPO

In section “1.2 What’s a Programming Language?”, it is written “exmaple” instead of “example”.

2013-05-16
58TYPO

line 1 on page- second test is wrong. should be third test

2013-05-16
141SUGGEST

“The same is true for methods clear,…”
I couldn’t find the list method clear in the help.

2013-05-16
168TYPO

Page 168, exercise 11, line 4 of docstring should read’remove_neg(numbers). ‘n’ in neg is typed ‘r’

2013-05-16
23SUGGEST

Hi, the text states that installation instructions are available at the URL http: //pragprog.com/titles/gwpy2/practical-programming
Followed the link but no instructions :(

2013-07-31We'll be adding those instructions before the book is in its final form.
183176TYPO

There is typo in foot note at the bottom.

This is the actual sentence in book,
“If you’re still note clear on how directory paths work, Wikipedia has a discussion: ”

I think you mean to say “not” instead of “note” in above sentence.

2013-07-06
254ERROR

in function find_largest() , return statement is wrong:

return copy[n:]
should be:
return copy[-n:]

2013-07-06
28TYPO

In the “Warning:= is not equality in Python!” box.
x is used as the example variable name until the last sentence where “degrees_celsius” is used. For consistency use “x equals 26.0.”

2013-07-06
2919SUGGEST

from regular integers

Please avoid using the American expression “regular” to mean normal. In this case the word seems redundant (as it mostly is when this word is used by Americans).

Thank you

2013-07-06
3525SUGGEST

“two kinds of errors in Python” >> there are two kinds of errors in Python

2013-07-06
4728SUGGEST

(as a reminder, focus only on the last line for now):

As we have not been told this before, it cannot be a reminder.

2013-07-06
39TYPO

as the Python style
recommends

>> as the Python style
guide recommends

{Apologies for getting PDF Page numbers incorrect in previous posts. )

2013-07-06
51SUGGEST

If the answer is “both integers and floating-
point numbers”, then use the word “number”.
What type of value is returned? An integer, a floating-point number,
or possibly either one of them?

{Is it possible you have the above two lines in the wrong order?}

2013-07-06
viiTYPO

Missing from Contents listing:
A1. The IDLE Development Environment
A2. Glossary
Bibliography

2013-08-07
90TYPO

>>> ‘A’ in ‘abc’
True # As the text notes, ‘in’ is Case-Sensitive, correct result is False

Context - Just prior to section 5.2

Operator in produces True exactly when the first string appears in the second string. This is case sensitive:
>>> ‘a’ in ‘abc’
True
>>> ‘A’ in ‘abc’
True
The empty string is always a substring of every string:
>>> ’’ in ‘abc’
True
>>> ’’ in ’’
True

2013-08-07
96SUGGEST

Context: Equivalence of
if condition:
if_block
else:
else_block
to
if condition:
if_block
if not condition:
else_block

Comment
Usually true, unless the if_block affects a variable used in the condition

pdf page 94 noted this exception
With the ph example, we accomplished the same thing with two if statements as we did with an if/elif. This is not always the case; for example, if the body of the first if changes the value of a variable used in the second condition, they are not equivalent.

Suggestion, on page 96 add this note
This is not always the case; for example, if the body of the first if changes the value of a variable used in the second condition, they are not equivalent.

2013-08-07
101ERROR

Question 11 asks why the last example on page 97 checks to see if someone is heavy. But the example code on page 97 has an assignment
slim = bmi < 22.0

11. Why does the last example in Section 5.4, Remembering Results of Boolean Expression Evaluation, on page 97 check to see whether someone is heavy (that is, that their weight exceeds the threshold) rather than light? If you wanted to write the second assignment statement as light = bmi < 22.0, what change(s) would you have to make to the lookup table?

Code from the end of page 97 (using boolean variables to remember the result of a comparison)

The expression bmi < 22.0 is used multiple times. To simplify this code, we can evaluate each of the Boolean expressions once, create variables that refer to the values produced by those expressions, and use those variables multiple times:

young = age < 45
slim = bmi < 22.0
if young:
if slim:
risk = ‘low’
else # NOTE missing COLON here as well on page 97 code
risk = ‘medium’
else:
if slim:
risk = ‘medium’
else:
risk = ‘high’

Comment
An elegant and readable way to handle nested comparisons
Code on page 97 needs a colon after one else
Question in exercises needs revision to stay consistent with current code on page 97.

2013-08-07
101ERROR

‘A’ in ‘abc’
True

2013-08-07
166ERROR

Minor technical error: bacteria are individual cells, not fractions.

The answer 2143.5888099999997 cannot be correct.

Of two possible fixes - use int or round of the added population - I lean towards the round solution

The program as written:
time = 0
population = 1000 # 1000 bacteria to start with growth_rate = 0.21 # 21% growth per minute
while population < 2000:
population = population + growth_rate * population
print(population)
time = time + 1
print(“It took”, time, “minutes for the bacteria to double.”) print(“The final population was”, population,“bacteria.”)

Suggested change to the line immediately follow the while statement
population = population + round(growth_rate * population)

Alternatively, just round the result, and add a comment about significant figures in experiments and computer simulations.

2013-08-07
167SUGGEST

Loop until the user enters quit
Suggestion - make a standard, or conanical, form of the input, testing user input made lowercase against the keyword quit

Context
text = “”
while text != “quit”:
text = input(“Please enter a chemical formula (or ‘quit’ to exit): ”)
if text "quit": print("...exiting program") elif text “H2O”:
print(“Water”)
elif text "NH3": print("Ammonia") elif text “CH4”:
print(“Methane”)
else:
print(“Unknown compound”)

Could allow for user typing Quit or QUIT or perhaps with CAPS LOCK key
qUIT

text = “”

  1. allow for possible variations on ‘quit’:
    while text.lower() != “quit”:
    text = input(“Please enter a chemical formula (or ‘quit’ to exit): ”)
    if text.lower() == “quit”:

Suggestion 2:
Leave the program as is, but have an exercise about making it more forgiving of slightly sloppy user input.

2013-08-07Nice -- we've added the exercise.
104TYPO

bottom of page
the if elif , can not find out how
to enter into idle without getting
SynataxError: unident does not match…

2013-08-07You may need to paste the example one line at a time into IDLE. IDLE automatically indents the first line of a block (e.g. after a "def", "if", "elif", etc). So when you paste in the "elif" line, you need to remove the indentation first, then paste. Hope this helps!
179TYPO

Missing a name for the short program created in IDLE to read a file

4. In IDLE, select File -> New Window and type (or copy and paste) this program:
[program text here]
5. Save this file as in directory file_examples

Change line 5 to something like this
5. Save this file as reader.py in directory file_examples

2013-08-07
183ERROR

Context: discussion of \
at end of lines derived from use of readlines

Current text
The last line of a file may or may not end with a newline character as you
learned in Section 7.3, Exploring String Methods, on page 123.

Problem
The excellent list of string methods in section 7.3 does not mention \
relating to files.

My observation: A reference back to 7.3 is a great suggestion; many of the string methods provide exactly what you need when processing text file strings.

Recommendation. Just refer the reader back to section 7.3 - Many of the string methods from section 7.3 will come in handy when processing strings from text files.

2013-08-07
204TYPO

Exercise 5 - word ‘it’ omitted

Current
5. Modify the file reader in read_smallest_skip.py of Skipping the Header, on page 189 so that can handle files with no data.

Change to add ‘it’ before ‘can handle’
5. Modify the file reader in read_smallest_skip.py of Skipping the Header, on page 189 so that it can handle files with no data.

2013-08-07
216ERROR

Context: explaining how tuple assignment allows a swap of variables

One of the most common uses of multiple assignment is to swap the values of two variables:
>>> s1 = ‘first’
>>> s2 = ‘second’
>>> s1, s2 = s2, s1
>>> s1
‘second’
>>> s2
‘first’
This works because assignment.

Sentence fragment instead of explanation.

I’d say something like

This works because assignment evaluates all the expressions on the right side of the = first (imagine them assigned to temporary variables _temp1 and _temp2), then assigns those results to the variables on the left of the = (s1 = temp1, then s2 = temp2). Result: variables get swapped.

But any explanation (or removing the sentence fragment) should fix it.

2013-08-07
90SUGGEST

When requesting to enter a date in the format DD MM YYYY, one could expect an answer like 24 02 2013 instead of 24 Feb 2013 like given in the book. MM stands for 2 positions. But it’s maybe a local cultural difference :-)

2013-08-07
90ERROR

WHERE Near end of section 5.1
WHAT Example of ‘in’

The in operator produces True exactly when the first string appears in the second string. This is case sensitive:
>>>‘a’ in ‘abc’
True
>>>‘A’ in ‘abc’
True

ISSUE ‘A’ in ‘abc’ produces False

FIX Change True to False in second example ‘A’ in ‘abc’

2013-08-07
35SUGGEST

The examples in 3.2. Add note to indicate that the answer to ‘Let’s try it:’ (object’s memory address) will probably be a different address.

2013-08-07
36TYPO

Last line " (focus only on the last line for now):" The example referred to is the FIRST line.

2013-08-07
24ERROR

2.6 examples of line-continuation. The line ‘triple-dot’ prompt does not appear in Python 3.3.2 Shell: Python 3.3.2 (v3.3.2:d047928ae3f6, May 13 2013, 13:52:24)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)].

2013-08-07This seems to only happen in IDLE. If you run the Python shell outside IDLE, those dots don't appear. Hmm...
37SUGGEST

Paragraph 3.
>>> def convert_to_celsius(fahrenheit):
… return (fahrenheit - 32) * 5 / 9

Need explanation for first appearance of “:” at end of line 1.
Need explanation for first appearance at line 3: a blank line.

2013-08-07
62SUGGEST

Introduction of “!=” in example:

Precondition: n != 0

Not is Index as symbol. Indexed as “Not operator”. Defined in text at page 84.

I suggest you add it to the Symbols in index and add note at the example.

2015-11-04
32TYPO

end of line 5, beginning of line 6: the word Python is repeated.

2015-11-04
11ERROR

“For the mathematically inclined, the relationship between // and % comes from this equation, for any two numbers a and b:
(b * (a // b) + a % b) is equal to a”

Insert “non-zero” between “two” and “numbers”, for when b = 0, a divide-by-zero error occurs.

2015-11-04
70TYPO

line 4 of the text reads: “using the *operator” — there should be a space after the “*”.

2015-11-04
71TYPO

Lines 4 and 5 explain that single quotes can be used for strings containing double quotes. Then lines 6 and 7 repeat that.

2015-11-04
72TYPO

Line 10 of the text contains: “Python creates contains a \
sequence” which should read “Python creates contains a \
escape sequence”.

2015-11-04
76SUGGEST

Line 1 of the text starts: “In an earlier chapter, we explored some built-in functions.” For clarity should read “In chapter 3, we explored some built-in functions.”

2015-11-04
51TYPO

There are 2 instances where the text in step “4. Description” doesn’t match the text in step “5. Body”. First, the latter ends with “which are” instead of with the word “both”. Second, the remainder of the sentence should be on the second line instead of passing “year).” to a third line. Defining the function with the docstring as it appears in “4. Description” returns the text as shown on page 51, after calling help on function “days_difference”.

2015-11-04
85TYPO

In the example at the bottom of the page the 5th to last line reads: “Return True iff x is positive.” This should be “Return True if x is positive.”

Author note: iff stands for “if and only if”.

2015-10-16
92TYPO

Last line of last example on page reads “print ”You should be careful with that!“”
which is not valid syntax. It should read: “print(”You should be careful with that!“)”

2015-11-04
90TYPO

In the second code example on the page:

>>> ‘a’ in ‘abc’
True
>>> ‘A’ in ‘abc’
True

The correct code should be:
>>> ‘A’ in ‘abc’
False

2015-11-04
90ERROR

The section describing the IN operator uses an example meant to illustrate the case sensitivity of the operator. However the example is wrong:

>>> ‘A’ in ‘abc’
True

If IN is case sensitive then the result of this example should be “false”. Running it in IDLE definitely shows a result of false as would be expected.

2015-11-04
111ERROR

The second to last code snippet on the page reads:

print(“After import, name is”, name, \\
“and echo.name is”, echo.name)

The escape character at the end of line 1 is not required because of the surrounding parenthesis.

2015-11-04
121TYPO

“Here are two more examples, this time using the other two string methods
from the code on page 119.”

Should be page 120.

2015-12-01
122ERROR

The code snippet at the top of the page:

>>> help(math.sqrt)
Help on built-in function sqrt in module math:

should be prefixed by:

>>> import math

to get it to work.

2015-11-04
125TYPO

The line:
these three functions to a string with leading and trailing whitespace:

“functions” should be replaced by “methods”

2015-11-04
90TYPO

About mid-page, example reports that the phrase, or whatever I should call it, ‘A’ in ‘abc’ is True. This violates the case sensitivity of things, and anyway, I get False when I run it.
Thanks

2015-11-04
96SUGGEST

I see that someone has already discussed this, but wouldn’t it be better the replace the phrase

“This code is the same as this:”

with

“is equivalent to”

?

Maybe too picky?

2015-11-04
90TYPO

as printed:

>>> ‘A’ in ‘abc’
True

should be:

>>> ‘A’ in ‘abc’
False

2015-11-04
97TYPO

Isn’t a colon missing in the first occurrence of “else” in the code at the bottom of the page?

2015-11-04
89TYPO

Comparing Strings.
The characters in strings are represented by integers: a capital A, for example, is represented by 65, while a space is 32, and a lowercase z is 172.

65 and 32 are decimal but the 172 is the octal for ‘z’, should be 122.

2015-11-04
146TYPO

In the box “Where did my list go?”:

“As we will discuss in Section 6.3, Testing Your Code Semiautomatically, on page 114”

should be:

“As we did discuss in Section 6.3, Testing Your Code Semiautomatically, on page 114”

2015-11-04
28SUGGEST

Fourth bullet point - It may be helpful to clarify the second sentence by explaining that the variable will now point to the new value.
I find it vague the way it is currently stated.

2015-11-04
90TYPO

[…] This is case sensitive:

is:
>>> ‘A’ in ‘abc’
True

should be:
>>> ‘A’ in ‘abc’
False

2015-11-04
32TYPO

“…refers to 10, Python
Python evaluates this expression to –7.”

Duplication of the word Python

2015-11-04
2828TYPO

“Variables must be assigned values before they can used in expressions.” the word “be” is missing

2015-11-04
90ERROR

The in operator produces True exactly when the first string appears in the
second string. This is case sensitive:
>>> ‘a’ in ‘abc’
True
>>> ‘A’ in ‘abc’
True

## second entry should read false

2015-11-04
177TYPO

In the last paragraph before 10.1:

“You’ll first learn how to open and read information from files. After that, you’ll learn about the different techniques for reading files,…”

Shouldn’t that be “different techniques for writing files,…”

2015-11-04
178TYPO

In the penultimate paragraph:

“calendar programs read and process ical files (),”

ical should be iCal and the “()”?

2015-11-04
180TYPO

First line of second paragraph:

“The second statement, contents = example_file.read(), tells Python that you want”

should read:

“The second statement, contents = file.read(), tells Python that you want”

2015-11-04
180TYPO

First line of third paragraph reads:

“The last statement, example_file.close(), releases all resources associated with”

and should be:

“The last statement, file.close(), releases all resources associated with”

2015-11-04
187TYPO

Section 10.4: all references to “urllib.urlrequest” are incorrect. The correct module name is “urllib.request”.

2015-12-01
180ERROR

2nd paragraph. The statements in the text a wrong. they are not the statements in the example.
2nd statement s/b contents = file.read()
last statement s/b file.close()
because these statements relate to the object “file” created by the open call.

2015-11-04
183ERROR

A call to function sum_number_pairs results in a TypeError. And before that module total needs to be imported.

[ Author note: In the paragraph before the function definition of sum_number_pairs, we mention that this code is saved in total.py. Once total is imported, the code works as shown. ]

2015-11-04
185TYPO

In the first paragraph, the line:

“programs using import tsdl, as shown in the next example. This allows us to”

should import time_series

2015-11-04
189TYPO

Top of page: “We now face the same choice as with skip_header: we can put find_largest in a module (possibly tsdl),”

The module name is “time_series” not “tsdl”.

2015-12-01
190TYPO

First paragraph: “here is the same code without using tsdl.skip_header and find_largest as helper methods:”

should be “time_series.skip_header”. This error occurs throughout this section.

2015-12-01
193ERROR

In example at the top of the page, file “multimol.pdb” is not closed.

2015-12-01
110TYPO

The whole of section 6.3 has an issue where the text refers to module temperature_program, which has 3 doctests, but the screenshots show the outcome of running doctest.testmod on module baking, which has 1 doctest.

2015-12-01
65SUGGEST

Nowhere in the description of strings is it mentioned that a string is a list of characters and that each character can be accessed by its index. I found this baffling when later strings were subscripted and looped over. Thanks to the Coursera forum I stumbled on the explanation.

[ Author note: The for loop over strings is introduced in section 9.2, but that section makes no mention of indices, because they aren’t used by the for loop. String indexing is briefly discussed in section 11.2. ]

2015-11-04
140TYPO

First paragraph: all references to “celegans_phenotypes” should be “celegan_markers”.

2015-11-04
171SUGGEST

Throughout the examples in this chapter newlines are removed using str.strip(). However in the Coursera course in the week 6 files exercise this is marked incorrect and str.rstrip(’\
) is used. The examples should probably be updated to show this more specific syntax.

Author note: thanks for pointing this out. It is something to consider for the next edition.

2015-12-01
186ERROR

In function definition smallest_value_skip there is no check for a ‘-’ in the first data line after the header.

2017-08-12This is a good point. We omitted this check because we assumed the first value would never be missing — otherwise, the series of values would simply start one later. We have added a clarification about this in the third edition.
185ERROR

The type contract for function definition smallest_value is incorrect as it returns an int.

2015-11-04
186TYPO

The type contract for function definition smallest_value_skip is incorrect as it returns an int.

2015-11-04
196ERROR

Not so much an error as a redundant check in function definition read_molecule:

if fields[0] == ‘ATOM’:

is redundant as with the format of the data file if not at the end of file and not at a new molecule the only other kind of line is a line that starts with ‘ATOM’.

Author note: Good point. Leaving it as is for this edition.

2015-12-01
12TYPO

The operator for type is not listed under section 2.3. Instead the operator * is listed twice.
Wrong: “these operators can be applied to those values: +, -,, /, //, %, and.”
Should have been: “these operators can be applied to those values: +, -,, /, //, %, and*.”

2015-11-04
94TYPO

In the docstring “Return True iff x is positive,” there’s an extra “f”

Author note: iff stands for “if and only if”.

2015-10-16
225TYPO

In “Find, Remove, Find” it is not the re-insertion that is the problem, but the removal, as min2 is obtained before the re-insertion.

2017-08-12Subtle point but valid! Very nice catch. We've updated the short description and the comments in the code in the upcoming third edition.
224TYPO

At the bottom of the page:
def find_two_smallest(L):
“”" (list of float) -> tuple of (int, int)

The type of the list in int not float. This error continues through all the examples in this section.

2015-12-01
230TYPO

Last example on page:

  1. Examine each value in the list in order
    for i in range(2, len(values)):

should be:

  1. Examine each value in the list in order
    for i in range(2, len(L)):
2015-12-01
233TYPO

In function definition:
def time_find_two_smallest(find_func, lst): the return statement has a period at the end of the statement.

Author note: The period makes the number a float. I updated it to be 1000.0

2015-12-01
233ERROR

In the example on the page the file is opened for reading but never closed.

2015-12-01
57TYPO

“2. Type Contract. The arguments in our function call examples are all inte- gers, and the return values are integers too,”

The return value is an integer.

2015-11-04
302TYPO

The test case pattern at the top of the page:

been
expected = «the value we expect will be returned»

What is the “been” on the first line doing there?

2015-11-04
304TYPO

Last paragraph on page:

Following those steps, we created a variable, nums

The variable in the docstring is “L” not nums". This error occurs throughout this paragraph.

2015-11-04
239TYPO

Bottom of page:

list[0:i] doesn’t contain value, and 0 <= i <= len(lst)

should be:

list[0:i] doesn’t contain value, and 0 <= i < len(lst)

as i should be 1 less than len(lst)

Author note: This is okay as is. In the body of the function, we do allow i to become equal to len(lst).

2015-12-01
243TYPO

function definition “time_it” has the type contract:

(function, object, list) -> number

which should be:

(function, list, object) -> number

2015-12-01
260TYPO

The doctest for function definition bin_sort is incorrect as the function returns a sorted copy of the list.

2015-12-01
174ERROR

(in “The with Statement” section)
A misleading oversimplification is given re. the purpose of the ‘with’ statement in Python: The book states that it “automatically closes a file when the end of the block is reached”. In fact, open() provides a context for ‘with’ to use with associated enter() and exit() methods; in this case it is the exit() method that will deal with closing the file. I’m still learning Python so that may not be 100% right, but I think it’s important not to give the impression that ‘with’ is just for closing files, but has much wider application, and also to at least hint at the mechanism underlying this.

2017-08-10Thanks for this. We've addressed this as we write the third edition.
111TYPO

Figure 5 shows the IDLE results of running baking.py, but the text discussing this on page 110 and the start of text on page 111 talks about temperature_program.py: I think Figure 5 needs to be updated to refer to temperature_program.py

Author note: related to #52967

2015-12-01
241TYPO

In the explanation of the function linear_search(), it says, “At the end, we return… len(list) if value wasn’t in list.”, but actually –1 is returned

2015-12-01
287TYPO

The example method at the bottom of the page:

def str(self):
“”" (Member) -> str

The type contract should be:

“”" (Faculty) -> str

2015-12-01
291TYPO

End of first paragraph reads:

rewritten to return a Molecule object instead of a list of tuples:

should be:

rewritten to return a Molecule object instead of a list of lists:

2015-11-04
343ERROR

The first line on the page:

The Python equivalent is a type we haven’t seen before called bytes…

This is incorrect. We were introduced to bytes on page 181, section 10.4:

There’s a hitch: because there are many kinds of files (images, music, videos, text, and more), the file-like object’s read and readline methods both return a type you haven’t yet encountered: bytes.

2015-11-03
360SUGGEST

Nowhere in this chapter are there instructions to close the connection to the database when you’re finished working with it:

con.close()

Had to figure out for myself that there had to be a way to close something that had been opened.

2017-08-25Thanks for reporting this. We've fixed it in the upcoming third edition.
328TYPO

First sentence of “Changing Colors”:

Almost all foreground colors can be set using the bg and fg keyword arguments, respectively.

Should be:

Almost all foreground and background colors can be set using the bg and fg keyword arguments, respectively.

2015-11-04
335TYPO

Last sentence before the code:

accessed using self.state, and its controllers are the methods upClick and quitClick.

the 2 method names are:

up_click and quit_click

2015-11-04
337TYPO

Question 5 states:

In Section 3.4, Using Local Variables for Temporary Storage, on page 39,

should be:

In Section 3.3, Defining Our Own Functions, on page 35,

2015-11-04
59ERROR

The first code example of section 3.7 reads:

>>> 3 + 5 / abs(–2)
5.5

When I type this into IDLE 3, the return value is 4.0, not 5.5.

[ Author note: I believe this is correct as is. Please double-check that you are using Python 3 and don’t add any additional parentheses.]

2015-11-04
85TYPO

The sentence ‘This is often referred to as or Python decides which string is greater than which by comparing corresponding characters from left to right.’ seems garbled.

[ Author note: I agree. There are a couple of words missing, so we’ll try to correct this. Thanks.]

2015-11-04
88ERROR

In the final example shouldn’t there be parentheses around the string to be printed?

[ Author note: do you mean print(ph, “is basic.”)? If so, that’s fine as is. ph is a variable and the value it refers to will be concatenated with the string “is basic”. ]

2015-11-04
233ERROR

sea_level_press = []
sea_level_press_file = open(‘darwin.slp’, ‘r’)
for line in sea_level_press_file:
sea_level_press.append(float(line))

I keep on getting the following error:
sea_level_press.append(float(line))
ValueError: could not convert string to float:

I have checked the data file and there are no extraneous spaces, etc. Yet I cannot get past this problem.

Any suggestions?

Author note: In a multiline file, all lines except possibly the last would have a newline character and that can’t be converted to an int. Try removing the whitespace from the end of the line like this: sea_level_press.append(float(line.rstrip()))

2015-12-01
213TYPO

“key/value pair listed is ‘canada goose’: 71” should be,
“key/value pair listed is ‘canada goose’: 183”

2015-12-01
371367ERROR

In the index for “backslash”, only the meaning of backslash in Windows directory paths is listed (P.174). The use of backslash as line-continuation (P.24) is not listed.

2017-08-11Nice catch! We've fixed this in the upcoming third edition. Thanks!
246TYPO

" while if it is greater than j, we should move j down." should be (i think), “while if it is greater than v, we should move j down.”

2015-12-01
246TYPO

‘because L[i] isn’t included in the range; instead…’ should be (i think), ‘because L[m] isn’t included in the range….’

2015-12-01
248SUGGEST

code related to binary search,
if name == ‘main’:
import doctest
doctest.testmod()

will not display output unless dockets.testmod() is enclosed in print (), i.e.
print(doctest.testmod())

Author note: It is not necessary to call on print. If tests fail, the output will be displayed.

2015-12-01
220TYPO

This is not an error in the book, but for the explanation of exercise 5 on page 220 (Storing Data Using Other Collection Types).

For the return, you should have - return name , but instead you have return particle - .

When called with

least_likely({’neutron’: 0.55, ‘proton’: 0.21, ‘meson’: 0.03, ‘muon’: 0.07})

instead of getting ‘meson’ you get ‘muon’

5.

def least_likely(particle_to_probability):
“”" (dict of {str: float}) -> str

Return the particle from particle_to_probability with the lowest probablity.

>>> least_likely({’neutron’: 0.55, ‘proton’: 0.21, ‘meson’: 0.03, ‘muon’: 0.07})
‘meson’
“”"

smallest = 1
name = ’’

for particle in particle_to_probability:
probability = particle_to_probability[particle]
if probability < smallest:
smallest = probability
name = particle

return particle

PS - Bought the book after the Coursera course (which was great). I have really been enjoying going through this book.

350SUGGEST

for c in countries:
cur.exec(‘INSERT INTO PopByCountry VALUES (?, ?, ?)’, (c[0], c[1], c[2]))
can be simply presented as,
cur.exec(‘INSERT INTO PopByCountry VALUES (?, ?, ?)’, c)
rather than presenting each element within the tuple

[Author note: Yes, either approach would be fine.]

2015-11-03
219ERROR

It’s most likely my error but when I run the first code under 11.3, “Storing Data Using Dictionaries”, the bird_counts[] list never populates. I ran it through the Python Visualizer and the code never runs past ‘found = False’. Is there something missing ???

Author note: It should be able to get past that assignment statement. I suggest checking the identation of the code. I’ll close this, but if you still have trouble, please consider posting your question to the forums.

2015-12-01
1SUGGEST

Would it be possible or desirable to provide the Exercise Solutions in a PDF or some other easily printable form?

2017-08-14There's now a link to the LaTeX version of the solutions (from which you can generate a PDF) from the main solutions wiki page.
81TYPO

“Return True iff x is positive.” - note extra ‘f’ in ‘if’.

Author note: iff stands for “if and only if”.

2015-10-16
257TYPO

Figure 13—First few steps in selection sort
=>
Figure 13—First few steps in insertion sort

2015-12-01
126ERROR

This is not an error with the text, but an error with the exercise solutions at http: // pragprog (dot) com/wikis/wiki/PracProg2methods.

Solutions for exercise 11 b and c read:
b.‘C02 H20’.find(‘0’)
c.‘C02 H20’.find(‘0’, ‘C02 H20’.find(‘0’) + 1)

Should be:
b.‘C02 H20’.find(‘2’)
c.‘C02 H20’.find(‘2’, ‘C02 H20’.find(‘2’) + 1)

The text asks for first and second occurrence of ‘2’ in ‘CO2 H2O’ (not ‘O’).

2015-11-04
91TYPO

Throughout the text, chemical compounds that include oxygen (H2O, H2SO4, CO2, etc) are written with a zero instead of a capital letter O.

For example: H20 should be H2O.

This may be a bit nitpicky, since this is not a chemistry textbook. However, your examples and exercises involve finding occurrences of certain characters in these strings.

2015-11-04
287TYPO

Variable paul = Faculty(‘Paul’, ‘Ajax’, ‘pgries@cs.toronto.edu’, ‘1234’) contains only string ‘Paul’, not ‘Paul Gries’ as suggested by the print(paul) command three lines below.

2015-11-04
282TYPO

In the example at the bottom of the page, the ISBN of book_1 and book_2 are the same, so ‘==’ cannot distinguish between them. Assume this has been reported.

2015-11-04
282TYPO

Previous submit not error, Sorry!

2015-11-04
338ERROR

Dear Sir
I have bought the PDF file (practical programming_p2_0.pdf) last month. Unfortunately there is no page “338” in my PDF data! Is there any mistake with page numbers?
I would like to receive this page(when it exists)!
Thank you very much in advanced and I look forward to her from you!
my email address: nazemeh.ashrafianfar@tu-clausthal.de
With best regards
Nazemeh

Author note: Your are quite right that there doesn’t seem to be a page 338. However, nothing seems to be missing. I’ll report this to our publisher.

2015-11-03
2612TYPO

=> “For example, in type int, the values are …, –3, –2, 1, 0, 1, 2, 3, … and we have seen that these operators can be applied to those values: +,, , /, //, %, and.”

Should read “+, -, , /, //, %, and*.”
The last symbol was rendered as a * rather than a for the exponent operator, thus showing multiplication twice.

2015-11-04
133SUGGEST

The bottom figure, the id2:str cell: “none” -> “neon”
It should be the result after the assignment to nobles[1].

(Author’s Note: Actually, the cell id2 never changes because strings are immutable. So cell id2 gets unlinked from the list and nobles[1] now points to cell id8 —Jason)

2015-11-04
137ERROR

Paragraph 4 - To remove Dpy and Sma, the list useful_markers has to be sliced differently:
>>> useful_markers = clelegans_phenotypes[0:4]
->
>>> useful_markers = clelegans_phenotypes[0:3]
The figure below presents it correctly.

2015-11-04
137ERROR

Sorry, my mistake. Only now I read further. Slicing in p.137 is correct.

2015-10-16
295287TYPO

In both of the str functions defined on this page, a string with new lines between each piece of data is returned. However, the docstring shows that the result should be a string with a backslash between each piece of data.

[Author note: Yes, there should be a newline character (\
) between each piece of data. The example shown in the docstring can be executed using a module named doctest. To do so, we import doctest and run doctest.testmod(). To express \
in a doctest, we need to escape the backslash, which is why it is written as \\\
.]

2015-11-04
11OK

It says “With // , the result is rounded down to the nearest whole number”, when in reality it returns the floor of the normal division beetween the floats. Example:
>>>30//11.0
2.0

30/11 is 2.72, its nearest whole number is 3, but 30//11.0 returns 2, the floor of 30/11

2017-07-21Thanks for reporting this. We are working on the third edition of the book and I was trying to address this, but I believe our wording is okay as is. We say "rounded down", not just "rounded".
24OK

((350-32) x (5/9)) /20 = 8.83333333333333 rather than 7.83333333333333 for oven-heating time.

2017-08-10In the expression above, you forgot to subtract 20: \n>>> (((350-32) * 5 / 9) - 20) / 20 \n7.833333333333333 \n
24OK

Erratum submitted in error. (–20) missing from numerator which changes result from 8.833…. to 7.833…. My apologies.

2017-08-10
103ERROR

I’m using PY3.5.2.
in the grey example “Restoring a Module,” I tried to follow the steps in my Shell. The math=imp.reload(math) line does not reset pi. It remains set to “3”. Oddly enough, your later example (bottom of page 106) had me reload my own module “experiment” which did work. I immediately retried the “pi” reset in vain. I’m confused. I did notice the hint popped, up when I was typing imp.reload, indicating “(module) depricated”. Futher Google searches on the subject had me trying other methods but they were all in vain as well.

2017-08-03Thanks for reporting this. As you point out, imp.reload is deprecated and has been replaced. Also, Python treats system modules and user-defined modules differently, and we will update this section in our third edition.
111TYPO

Figure 4-The doctest Module Running the Tests from Module temperature_program is the wrong snapshot… it is showing a test of the baking.py program not the temperature program.

2017-08-13Thanks for catching this! Yes, the figure doesn't match the text. We'll have this fixed in the next edition.
113TYPO

Figure 6—Failure Message for doctest is showing test result from the baking.py program and not the described temperature_program.py module. The explanation doesn’t match the figure either. It’s clearly just the wrong snapshot.

2017-08-13Thanks for catching this one too! We'll have it fixed in the next edition.
183ERROR

Current statement in the book, p2.0 page 183, will result error message (ValueError: could not convert string to float: ). Suggest to add one line to read input_file.

with open(output_filename, ‘w’) as output_file:
with open(input_file, ‘r’) as input_file:
for number_pair in input_file:………….

2017-08-10I understand your question, I think. This is subtle: the first parameter, input_file, is an open file, while the second parameter, output_filename, is a string containing the name of a file.
85TYPO

I’ve purchased the book and I believe I have found an editing error. It’s in Chapter 5.1 A Boolean Type, p 85, “Comparing Strings” (2nd paragraph). It says:

One of the most common reasons to compare two strings is to decide which one comes first alphabetically. This is often referred to as or Python decides which string is greater than which by comparing corresponding characters from left to right. (italics mine)

I believe there is something missing after “This is often referred to as…”.

2017-07-26Thanks for reporting this issue. There was a formatting problem that hid some text. This will be fixed in the third edition of the book.
62TYPO

the first line:
`Reading the code, if someone calls pie(0) , then you probably see that this will`

pie(0) should actually be `pie_percent(0)`.

2017-08-10Thanks for this, we'll update this in the third edition.
76TYPO

In Chapter 4 - Working with Text Answer 5a and 5b rabbit has too many “b’s”
rabbbit should be rabbit.

2017-08-14Thanks for catching this! We've updated the solutions.
195185TYPO

the return type for smallest_value should be changed to int, not NoneType, as there is an int value being returned

2017-08-12Thanks for this, we've addressed it it the upcoming third edition.
226ERROR

• 216
observations_file = open(‘observations.txt’)
bird_to_observations = {}
for line in observations_file:
bird = line.strip()
bird_to_observations[bird] = bird_to_observations.get(bird, 0) + 1
observations_file.close()
+
>>> # Print each bird and the number of times it was seen.
… for bird, observations in bird_to_observations.items():

print(bird, observations)

After executing the above code I’ve got just one bird - key , value - pair.

10TYPO

Near bottom of the page, is the statement - “If you want, you can omit the zero after the decimal point when writing a floating point number:” The answers given are (17 - 10. and 17. - 10) which both equal (7.0) - I would think that the zero (0) after the decimal point would be gone instead of both equations equaling the same 7.0 answer. Should they both be 7?

18TYPO

On page 18, first full paragraph, you state variable degree_celsius when it should be degrees_celsius as in the preceding examples. (degree_ vs degrees_) Yes - I am a retired Navy cryptographer so I do pick out even the smallest of things.

257TYPO

Figure 13 should be say insertion sort instead of selection sort.

107ERROR

Hi, The error is in the pdf of the answers of the exercises from chapter 5, not in the pdf of the book.

There are answers to only 5 items in question 1, but there are 8 items in the book.
The answers should go from a to h, but there’s only this:
a.True
a.NameError
a.True
a.True
a.True

149TYPO

In the text you use the name celegans_phenotypes and in the image you use the name celegans_markers

180ERROR

Exercise 16, a)
You say that the rat_1_weight contains the weight of the rat, it means that it is a variable that holds an integer, but in the answer, you use: rat_1_weight[week]
Are you trying to iterate over a number? It doesn’t make sense. It obviously returns an error: TypeError: ‘int’ object is not subscriptable

7259TYPO

“Now open IDLE, select File→New Window, and type this program in. (Either that or download the code from the book website and open the file.)”

What I think it should be is as follows:

Now open IDLE, select File→New File

Categories: