Section 7.15 Traversal and the while
Loop
The while
loop can also control the generation of the index values. Remember that the programmer is responsible for setting up the initial condition, making sure that the condition is correct, and making sure that something changes inside the body to guarantee that the condition will eventually fail.
The loop condition is position < len(fruit)
, so when position
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.
Here is the same example in codelens so that you can trace the values of the variables.
When you traverse a string with
for
by item (as in
Section 7.13), you have to process every character
1 . With
while
, you don’t have to process the entire string, You can set a condition to exit the loop before the whole string is processed. Here is a program that prints every character in a string up to the first space:
Checkpoint 7.15.1.
How many times is the letter o printed by the following statements?
s = "python rocks"
idx = 1
while idx < len(s):
print(s[idx])
idx = idx + 2
0
- Yes,
idx
goes through the odd numbers starting at 1. “o” is at position 4 and 8.
1
- “o” is at positions 4 and 8.
idx
starts at 1, not 0.
2
- There are 2 “o” characters, but they are at even index positions, and
idx
takes on only odd index values.
unless you use break
, which is not encouraged