6.3: Traversal through a string with a loop
- Page ID
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
index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1
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.
Exercise 1: Write a
while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
Another way to write a traversal is with a
for char in fruit: print(char)
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.