Repeating over a Sequence
Learning Objectives
- You can use a
forloop and conditions to process characters in a string. - You can build a count or a text result across loop iterations.
- You can use
range(...)for a fixed number of repetitions or to visit string indexes. - You can trace a loop one iteration at a time, following the loop variable and any remembered results.
The previous chapter ended by printing the characters at indexes 0, 1, 2, and so on. That required a separate statement for every position and only worked for one particular word length.
The purpose was simple: do the same thing once for every character. Python has a direct way to express that idea.
Your First for Loop
The output is:
pythonRead the loop as:
For each character in
word, print that character.
The indented block is the loop body. Python runs it once for each item in the sequence.
The name character is the loop variable. On the first iteration it refers to "p", on the second to "y", and so on.
You choose the loop-variable name. This works too:
for letter in word: print(letter)letter communicates the purpose more clearly than a vague name such as x.
A loop runs once for every item. If the string is empty, it has no items, so the loop body runs zero times. A program that only prints inside such a loop prints nothing for an empty word.
Arrange the blocks of a short program before writing your own loop. Notice which statement runs once before the loop, which statement repeats, and which statement runs after it.
Put the loop in order
0 / 3 points
Arrange the Python blocks so the program stores the word go, prints its characters one per line, and finally prints Finished. The indented printing statement belongs to the loop and moves with it.
Now write a loop that prints the characters of an entered word.
Print every character
0 / 10 points
Complete the program so it reads one word without a visible input prompt and prints every character on its own line, in the original order.
Use a direct for loop over word, with the loop variable representing the current character. The starter removes whitespace around the word; otherwise preserve every character exactly, including its letter case. A repeated character must be printed once for each time it occurs. If the entered word is empty, the program should print nothing.
You can also describe the same loop in plain language. Arrange the steps so the generated program stores a short word and prints each character.
Printing characters with natural-language programming
0 / 5 points
Drag and drop the natural-language programming steps to the area marked with “Program”. Arrange the steps so the program stores the word “hi” and prints each of its characters on a separate line.
One of the blocks is a loop. Drag the printing step inside the loop body. Some of the blocks are not needed.
Trace One Iteration at a Time
Consider:
word = "ivy"
for character in word: print(f"Character: {character}")A trace can be written as:
| Iteration | character | Output |
|---|---|---|
| 1 | "i" | Character: i |
| 2 | "v" | Character: v |
| 3 | "y" | Character: y |
On each iteration, Python assigns the next character to character and runs the loop body. Trace those assignments in order, as you traced changing variable values in Part 1.
Doing Something with Each Character
The body can contain any code appropriate for the current character:
word = "hello"
for character in word: print(character.upper())The output is:
HELLOThe loop does not change word. Each iteration takes one character, produces an uppercase version, and prints it.
Conditions Inside Loops
Everything you learned about if statements still applies inside a loop.
word = "banana"
for character in word: if character == "a": print("Found an a!")The condition is checked once per iteration. The message is printed on the iterations where the current character equals "a".
This is an important combination:
A loop decides when to repeat. An
ifdecides what to do on a particular repetition.
Print the vowels
0 / 10 points
Complete the program so it reads one word without a visible input prompt, normalizes it with .strip().lower(), and prints each vowel on its own line.
Use a direct for loop over the word. Inside the loop, use membership in the string "aeiou" to decide whether to print the current character. Preserve the vowels’ order and repetitions. If the word contains no vowels, print nothing.
Remembering Across Iterations
Sometimes printing something on each iteration is not enough. You need the program to remember what has happened so far.
Suppose you want to count the letter s:
word = "season"s_count = 0
for character in word: if character == "s": s_count = s_count + 1
print(s_count)The output is:
2The initialization s_count = 0 runs once, before the loop. Putting it inside the loop would reset the count on every iteration. Initializing it before the loop also gives it a value when the word is empty and the loop body never runs.
Trace the important values:
| Character | Is it s? | s_count afterwards |
|---|---|---|
s | yes | 1 |
e | no | 1 |
a | no | 1 |
s | yes | 2 |
o | no | 2 |
n | no | 2 |
This pattern has three parts:
- initialize a variable before the loop;
- update it on relevant iterations;
- use the final value after the loop.
You will reuse this pattern with lists later in the part.
The title of this part describes exactly what happens in the example above.
The for loop performs the repeating. The variable s_count performs the remembering.
Many useful loop algorithms are combinations of those two ideas.
Joining Strings with +
Before building a longer string in a loop, note that + has a useful meaning when both values are strings: it joins them together.
first_part = "rain"second_part = "bow"word = first_part + second_part
print(word)The output is:
rainbowJoining strings in this way is called concatenation. The operation does not add a space automatically. It simply places the second string immediately after the first one.
Building a Result One Character at a Time
A variable can also remember text:
word = "robot"result = ""
for character in word: result = result + character.upper()
print(result)The value of result develops like this:
"""R""RO""ROB""ROBO""ROBOT"This is another example of state changing across iterations.
You do not need to use this technique for every text-processing task. Its value here is that it makes the changing state visible.
Build a highlighted word
0 / 15 points
Complete the program so it reads one word without a visible input prompt and builds a highlighted version of it.
Normalize the word with .strip().lower(). Initialize highlighted to an empty string before a direct loop over word. During each iteration:
- join the uppercase version of the character onto
highlightedwith+when it is a vowel; - otherwise join the character unchanged onto
highlighted.
Hint: You can create a variable such as vowels = "aeiou". As you go through the characters in word, use membership to check whether the current character is in vowels.
Print the completed highlighted value once, after the loop. For example, education becomes EdUcAtIOn, while rhythm remains rhythm.
Remembered State and Empty Strings
You have already seen that a loop over an empty string runs zero times. This also means that any state initialized before the loop keeps its initial value:
word = ""result = "No characters"
for character in word: result = character
print(result)The assignment inside the loop never runs, so the program prints:
No charactersThe same reasoning applies to a counter initialized to 0 or a result initialized to "": if there are no iterations, its value does not change. This observation becomes important with lists too. Always consider what a loop does when its sequence is empty.
Check what a counter contains after a loop over an empty string.
Repeating a Fixed Number of Times
So far, each for loop has processed the items in an existing string. Sometimes you instead want to repeat an action a known number of times. The range(...) function provides the numbers a loop can use for this:
for number in range(3): print(f"Repetition {number + 1}")The output is:
Repetition 1Repetition 2Repetition 3range(3) provides the values 0, 1, and 2. Its stopping value, 3, is not included. The loop therefore runs three times. More generally, range(n) provides the values from 0 through n - 1, so its body runs n times when n is a non-negative integer.
Use a direct loop when you already have the values to process:
for character in word: print(character)Use range(n) when the main idea is to repeat an action n times:
for number in range(5): print("Keep practising!")In the second example, the loop variable is not needed in the body. It still receives the next number on every iteration.
Every statement in the loop body repeats. This includes reading input:
for number in range(2): answer = input() print(f"You entered: {answer}")This program reads and responds to two input lines because both statements are inside the loop. Moving input() before the loop would read only once, while moving it after the loop would postpone the read until both iterations were finished.
The values from range(5) can do more than control five repetitions. They are 0, 1, 2, 3, and 4, so number + 1 can label output for people as messages 1 through 5. The next exercise uses both roles to build a tiny event announcer.
Five-message announcer
0 / 10 points
Write a program for an event announcer. It must read exactly five messages, one per input line. Use input() without a visible prompt and one for loop over range(5).
On each iteration, read one message and immediately announce it in uppercase. Number the output from 1 through 5 by displaying the current range value plus one.
Preserve spaces and punctuation in each message. An empty message still gets its own numbered output line. Announce each message before asking for the next one.
For these inputs:
WelcomeGet readySetCodeCelebratethe output must be exactly:
MESSAGE 1: WELCOMEMESSAGE 2: GET READYMESSAGE 3: SETMESSAGE 4: CODEMESSAGE 5: CELEBRATEProduce exactly five output lines in input order. Do not write five separate copies of the input and output statements.
Using Range Values as Indexes
The numbers from range(...) can also serve as positions. Because range(len(word)) provides the values from 0 through len(word) - 1, it provides every valid non-negative index of the string:
word = "code"
for index in range(len(word)): print(f"{index}: {word[index]}")The output is:
0: c1: o2: d3: eDirect iteration is clearer when a program needs only each character. Using indexes is useful when the position itself matters or when the program calculates which position to inspect.
The following exercise asks you to explain a related indexed loop in plain language.
Explain an indexed loop
0 / 10 points
Explain in plain language what this program does:
word = "hello"
for i in range(len(word)): print(word[-1 - i])In three or four sentences, describe the values that i takes, how -1 - i selects characters, and what the program prints. Focus on the program’s behavior rather than merely listing its syntax.
Check Your Understanding
- What value does the loop variable have during one iteration of a
forloop? - Why is a counter usually initialized before the loop rather than inside it?
- How many times does a
forloop over an empty string execute its body? - Which values does
range(4)provide, and why does a loop over it run four times? - When would you choose
for item in sequenceinstead offor number in range(n)? - Why does
range(len(word))provide valid non-negative indexes forword?
AI Study Aid
Create a chapter diagram
We're looking into to what extent AI-generated diagrams could help with studying.
Use this study aid to generate an AI-generated visual summary of the material you just studied.
Each diagram style emphasizes the content in a different way, so you can choose the focus
that feels most useful.
Using the diagram generator is voluntary and does not affect your course progress. We encourage
you to try it out and see if it helps, but it's totally up to you! Your answers help us understand
how to make better study aids in the future.