9.12. 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.

 
1
fruit = "apple"
2
3
position = 0
4
while position < len(fruit):
5
    print(fruit[position])
6
    position = position + 1
7

(ch08_7c)

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.

Python 2.7
1fruit = "apple"
2
3position = 0
4while position < len(fruit):
5    print(fruit[position])
6    position = position + 1
Step 1 of 18
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(ch08_7c1)

Check your understanding

strings-12-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




Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

3
 
1
2
3

(scratch_08_02)

Next Section - 9.13. The in and not in operators