Chapter 7. Iteration and Search
In 1939, Ernest Vincent Wright published a 50,000-word novel called Gadsby that does not contain the letter “e.” Since “e” is the most common letter in English, writing even a few words without using it is difficult. To get a sense of how difficult, in this chapter we’ll compute the fraction of English words have at least one “e.”
For that, we’ll use for
statements to loop through the letters in a string and the words in a file, and we’ll update variables in a loop to count the number of words that contain an “e.” We’ll use the in
operator to check whether a letter appears in a word, and you’ll learn a programming pattern called a “linear search.”
As an exercise, you’ll use these tools to solve a word puzzle called “Spelling Bee.”
Loops and Strings
In Chapter 3 we saw a for
loop that uses the range
function to display a sequence of numbers:
for
i
in
range
(
3
):
(
i
,
end
=
' '
)
0 1 2
This version uses the keyword argument end
, so the print
function puts a space after each number rather than a newline.
We can also use a for
loop to display the letters in a string:
for
letter
in
'Gadsby'
:
(
letter
,
end
=
' '
)
G a d s b y
Notice that I changed the name of the variable from i
to letter
, which provides more information about the value it refers to. The variable defined in a for
loop is called the loop variable.
Now that we can loop through the letters in a word, we can check whether it contains the letter “e”:
for
letter
in
"Gadsby"
:
if
Get Think Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.