Section 7.3 Traversal through a string with a loop
A lot of computations involve processing a string one character at a time. Often, they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a
while
loop:This loop traverses the string and displays each letter on a line by itself. The loop condition is
index < len(fruit)
, so when index
is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1
, which is the last character in the string.Another way to write a traversal is with a
for
loop:Each time through the loop, the next character in the string is assigned to the variable
char
. The loop continues until no characters are left.Checkpoint 7.3.2.
- 0
- Incorrect! "strawberry" has two consecutive r's, so the way the loop is set up, this answer is impossible. Try again.
- 1
- Correct! idx starts at 1 and continues to the next odd number. There is only one 'r' whose index is an odd number.
- 2
- Incorrect! This would be true if idx started at 0. Try again.
- 3
- Incorrect! This would be true if idx incremented by 1 each loop. Try again.
11-9-4: How many times is the letter βr' printed by the following statements?
s = "strawberry"
idx = 1
while idx < len(s):
print(s[idx])
idx = idx + 2
Checkpoint 7.3.3.
- 10
- Incorrect! Iteration by item will print "HELLO" once for each character in the string. Try again.
- 11
- Incorrect! The space is part of the string, so "HELLO" will be printed for it as well. Try again.
- 12
- Correct! There are 12 characters in the string, including the space, and "HELLO" is printed once for each character.
- Error, the for statement needs to use the range function.
- Incorrect! The for statement can iterate over a sequence item by item. Try again.
11-9-5: How many times is the word HELLO printed by the following statements?
s = "green grapes"
for ch in s:
print("HELLO")
Checkpoint 7.3.4.
- 1
- Incorrect! This program only prints the characters at even index positions. Try again.
- 2
- Correct! It will print all the characters at even index positions and the i character appears twice in an even location.
- 4
- Incorrect! The for loop visits each index but the if statement means only some of their values are printed. Try again.
- Error, the for statement cannot have an if in its body.
- Incorrect! for statements can have any kind of statements in their bodies, including if statements. Try again.
11-9-6: How many times is the letter i printed by the following statements?
s = "mississippi"
for idx in range(len(s)):
if idx % 2 == 0:
print(s[idx])