6.3: Traversal through a string with a loop

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.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:

    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 loop:

    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.


    This page titled 6.3: Traversal through a string with a loop was last modified on Tue, 01 Dec 2020 03:50:53 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.