Repeating and Remembering

Choosing and Combining Repetition


Learning Objectives

  • You can choose a loop form for a task and explain why it fits.
  • You can split text into a list of strings and convert the items when you need numbers.
  • You can compare corresponding or neighboring list items without using invalid indexes.
  • You can combine input, lists, loops, and conditions in one program.

You now know several ways to repeat work. In this chapter, you will choose a loop that fits the task and use .split() to turn a line of text into a list.

Turning Text into a List with .split()

input(...) returns one string even when the line contains several words. The string method .split() can put those words into a list:

Inside a Python string literal, \t represents one tab character. A tab is a kind of whitespace, like a space. You can run this example to see how .split() treats both:

No files opened Select a file to edit

The output is:

['red', 'green', 'blue']

Without an argument, .split() separates at whitespace. Repeated spaces, tabs, and whitespace at the beginning or end do not create empty items. Text with no words produces an empty list.

The result is an ordinary list, so it can be processed with a loop:

words = input("Words: ").split()
for word in words:
print(len(word))

Splitting at a Specific Separator

An argument to .split(...) selects an exact separator:

text = "draft | review | publish"
steps = text.split("|")
print(steps)

This produces:

['draft ', ' review ', ' publish']

The separator is removed, but surrounding spaces remain. Unlike .split() without an argument, .split("|") does not also treat whitespace specially. When those spaces are not part of the data, strip each item while processing it:

for step in steps:
print(step.strip())

Two adjacent separators also leave an empty string between them. For example, "one,,three".split(",") produces ['one', '', 'three']. The next exercise avoids that case by guaranteeing a nonempty cargo name between every pair of commas.

Simple splitting is suitable for controlled text. Real file formats such as CSV have additional rules; later in the course, you will use tools designed for them.

Clean a cargo manifest

0 / 10 points

Write a program that reads one line containing one or more cargo item names separated by commas. An item name can contain spaces, such as oxygen tanks. You may assume that every item contains at least one non-space character.

Use .split(",") to create a list called items. First print the number of items in this exact form:

Item count: 3

Then use a direct for loop over items to print every item on its own line, in the original order. Apply .strip() to each item as you print it because delimiter-based splitting does not remove surrounding spaces. Use input() without a visible prompt.

Preserve the letter case and all whitespace inside each name, including repeated spaces. Only whitespace at the beginning or end of an item should be removed.

For input oxygen tanks, repair kit, water, the complete output must be:

Item count: 3
oxygen tanks
repair kit
water

Your program must also work when there are no spaces around the commas, when an item has spaces on both sides, and when the manifest contains only one item.

Choosing a Loop Form

Match the form of repetition to the information the task provides:

NeedTypical form
process each item in a sequencefor item in sequence
work with or replace items by positionfor index in range(len(sequence))
repeat a known number of timesfor ... in range(...)
repeat until an input or event says to stopwhile True with break

For example, values are enough when printing every city:

for city in cities:
print(city)

Positions are needed when replacing items in an existing list:

for index in range(len(stock)):
if stock[index] == 0:
stock[index] = 10

When there is no sequence but the count is known, range(...) can express the count directly. When neither a completed sequence nor a fixed count exists, user input can instead decide when a while True loop breaks.

These are guidelines, not laws. Prefer the form that makes the reason for repetition easiest to understand.

Combining Splitting and Repetition

The items produced by .split() are strings. Convert them when the program needs numbers:

pieces = input("Prices: ").split()
prices = []
for piece in pieces:
price = int(piece)
prices.append(price)

Once conversion is complete, a second loop can process the numeric list:

expensive_count = 0
for price in prices:
if price >= 100:
expensive_count = expensive_count + 1

Each loop has one job. The first turns the text pieces into numbers; the second counts prices of at least 100. If the input contains no words, both loops run zero times.

You could also update the count while converting the input. Both designs can work. In the next exercise, choose your own approach and explain to yourself what each loop does before writing it.

Parse and count temperatures

0 / 20 points

Write a program that reads one line containing zero or more whitespace-separated whole-number temperatures. You may assume every text piece is a valid whole number.

Print the temperatures as a list of integers in input order, followed by the number of values below zero. A temperature of exactly zero is not below zero. Keep repeated values.

Inputs may include a leading + or - sign or leading zeros. Compare the numeric values after conversion: for example, -0 is zero and +3 is positive.

For input -3 0 8 -1, print:

Temperatures: [-3, 0, 8, -1]
Below zero: 2

For an empty line or a line containing only whitespace, print:

Temperatures: []
Below zero: 0

Use input() without a visible prompt. The starter splits the input into text pieces. Decide how to turn those pieces into numbers, which loop form fits, and when to update the count. You may count during conversion or process the completed list afterwards.

Before coding, describe what your loop or loops will do. Then test a single zero, several negative values, repeated values, and input containing extra spaces or tabs.

Comparing Corresponding Items

Sometimes two lists describe the same positions. For example, one list can contain the words in a reference sentence while another contains the words someone typed. If the lists are equally long, an index can select the corresponding item from each list:

reference_words = ["red", "green", "blue"]
typed_words = ["red", "blue", "green"]
for index in range(len(reference_words)):
reference_word = reference_words[index]
typed_word = typed_words[index]
print(f"{reference_word}: {typed_word}")

The indexes start at zero and stop before len(reference_words), so every valid position in that list is visited exactly once. This pattern requires typed_words to have the same length: an index that is valid for one list is not automatically valid for another. The next exercise guarantees equal word counts so that you can focus on the corresponding-position comparison.

Comparing the two current items is different from asking whether a word occurs anywhere in the other list: position matters. In the next exercise, the starter prepares the word lists, and your task is to count the matching positions.

Compare two texts

0 / 15 points

Write a program that reads two lines of text and counts the positions where they contain the same word. You may assume that the two lines contain the same number of words.

Ignore letter case and repeated or surrounding whitespace. The starter prepares the two word lists for you. Preserve the word order: a word in the wrong position does not count as a match.

Use a loop to compare the corresponding positions and calculate the count.

For the two lines red green blue and RED blue green, print:

Correct positions: 1 of 3

Use input() without visible prompts and print only the result in this format. Your program must also handle two empty or whitespace-only input lines, producing Correct positions: 0 of 0.

Why is checking corresponding positions different from checking whether a value occurs anywhere in another list?

Comparing Neighboring Items

Some questions concern the relationship between consecutive items rather than one item at a time. For a list named cards, a comparison can use cards[index] and the item immediately to its right, cards[index + 1].

The final card has no right-hand neighbor. Therefore, the useful left-hand positions come from:

range(len(cards) - 1)

For five cards, this produces the indexes 0, 1, 2, and 3. Adding one gives the valid neighboring indexes 1, 2, 3, and 4; the loop never tries to read position 5.

Practise this neighboring-item pattern in the next exercise. Combine the comparisons with the boolean flag from Chapter 5 to inspect a rack of cards. Before coding, identify the pairs you will compare and when the flag needs to change.

Inspect a five-card rack

0 / 15 points

The starter reads five whole-numbered cards, one per line, and stores them in cards.

A rack is strictly increasing when every card is smaller than the card immediately to its right. Equal neighboring cards do not count as increasing. Determine whether the rack is strictly increasing without changing the order of its cards.

For inputs 3, 8, 12, 17, and 21, print:

Strictly increasing: True

For inputs 3, 8, 8, 17, and 21, print:

Strictly increasing: False

Practise the neighboring-item loop and Boolean flag from the material. Before running your program, predict the result for equal neighbors, a decrease near the beginning, and a decrease in the final pair.

Why does a neighboring-item loop use range(len(values) - 1) for its left-hand positions?

Explain the Choice, Not Just the Syntax

A useful explanation connects the control structure to the job it performs. For example:

The first loop uses while True because the user decides how many destinations to enter. After collection ends, the direct for loop visits every saved destination once, and no indexes are needed.

This says more than merely listing that the program contains while, break, and for. It explains what is known before each phase and why the chosen loop fits.

Explain two loop choices

0 / 15 points

Explain this program in natural prose. Assume that the user enters one word on each input line, possibly with whitespace around it.

words = []
while True:
word = input().strip()
if word.lower() == "done":
break
words.append(word)
long_words = []
for word in words:
if len(word) >= 5:
long_words.append(word)
print(f"Recorded: {len(words)}")
print(f"Long words: {len(long_words)}")

Explain what the program collects and prints, why while True with break fits the first phase, and why direct for iteration fits the second phase. Also explain why done is not stored, whether a five-character word is counted as long, and what both output lines contain if the user enters done immediately.

Focus on the purpose, state, and control flow rather than merely listing Python syntax.

Check Your Understanding

  1. What does .split() produce, and what type does each resulting item have?
  2. How does .split(",") differ from .split()?
  3. When is direct iteration clearer than using indexes?
  4. Which loop form naturally fits an interaction that continues until a stopping command?
  5. Why might you collect values first and process the completed list in a separate loop instead of counting selected values during input?

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.

Diagrams tried: 0