Traversal throught a string with a loop

Computations often involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something operation on it, and continue until the end. This pattern of process is called traversal. One way to write a traversal is with a while loop:
word = 'hello'
index = 0
while index < len(word):
    letter = word[index]
    print letter
    index = index + 1
h
e
l
l
o


This while loop traverses the string  and displays each letter on a line by itself. The loop condition is index < len(word), 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(word) -1, which is the last character in the string.
Example – 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 but backwards.
index = len(word)-1
while index >= 0:
    letter = word[index]
    print letter 
    index = index - 1
o
l
l
e
h
Another shorter way to write a traversal is with a for loop.
for char in word:
    print char
h
e
l
l
o
Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until there are no characters in a string left. 

Nema komentara:

Objavi komentar