Question
8.3 Traversal with a for loop A lot of computations involve processing a string one character at a time. Often they start at the beginning,
8.3 Traversal with a for 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 doesnt run. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string. As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line. Another way to write a traversal is with a for loop: for letter in fruit: print(letter) fruit b a n a n a index 0 1 2 3 4 5 6 Figure 8.1: Slice indices.
Each time through the loop, the next character in the string is assigned to the variable letter. The loop continues until no characters are left. The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskeys book MakeWay for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:
prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: print(letter + suffix)
The output is: Jack Kack Lack Mack Nack Oack Pack Qack Of course, thats not quite right because Ouack and Quack are misspelled. As an exercise, modify the program to fix this error.
1. Consider the loop from Section 8.3 of your textbook.
prefixes = 'JKLMNOPQ' suffix = 'ack'
for letter in prefixes: print(letter + suffix)
Put this code into a Python script and run it. Notice that it prints the names "Oack" and "Qack".
Modify the program so that it prints "Ouack" and "Quack" but leaves the other names the same.
Include the modified Python code and the output in your submission.
2. Give at least three examples that show different features of string slices. Describe the feature illustrated by each example. Invent your own examples. Do not copy them for the textbook or any other source.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started