Repeating Until We Decide to Stop
Learning Objectives
- You can use
while Trueto start repetition whose length is not known beforehand. - You can use
breakto leave a loop when a stopping condition is reached. - You can collect an unknown number of user inputs into a list.
- You can explain the different roles of
while Trueandforin a data-entry program. - You can reason about what happens when the user stops immediately.
A for loop works especially well when there is already a sequence to process:
for score in scores: print(score)Sometimes that sequence does not exist yet. A program might need to ask for tasks until the user enters an empty line. The program cannot know beforehand whether the user will enter two tasks, five tasks, or none.
This is a natural use for a while loop.
Repeating Without Knowing the Count
The condition in while True is always true, so the loop needs an explicit way to stop. Here, the empty string is a sentinel: a special value that ends input and is not part of the collected data.
When break runs, Python immediately leaves the loop and continues with the first statement after it. Read the structure as:
Ask for a value. If it means “stop,” leave the loop. Otherwise, remember it and repeat.
Keep the Sentinel Out of the Data
The order inside the loop matters. Each iteration should:
- read the next value;
- check whether it is the sentinel and break if it is;
- append it only when it is actual data.
If the append happens before the check, the stopping value becomes part of the list. If the user enters the sentinel immediately, the correctly ordered loop runs once but leaves the list empty.
Repair the sentinel loop
0 / 5 points
The program reads words until the user enters an empty line, then prints the collected list. Its statements are currently in the wrong order, so it stores the empty sentinel in the list.
Repair the loop so it checks for the empty string and executes break before appending an actual word. Keep input() without a visible prompt and print only the final list.
For the inputs red, green, and then an empty line, the output must be:
['red', 'green']If the first input is empty, the output must be [].
A Text Sentinel with Numeric Data
When the data is numeric but the sentinel is a word, keep the input as text until after the stopping check:
lap_times = []
while True: text = input("Lap time (finished to stop): ").strip().lower()
if text == "finished": break
lap_times.append(float(text))Calling .strip().lower() lets inputs such as Finished work as the same command. Only text that represents an actual lap time reaches float(...).
During Parts 1 and 2, you may assume that values expected to be numeric are entered in a valid numeric form. Part 3 introduces more systematic validation and exception handling.
Collect scores until stop
0 / 15 points
Write a program that reads an unknown number of whole-number scores, one per input line. The word stop ends data entry and is not a score.
Start with an empty list called scores. Use while True and break to collect the scores. Keep each input as text long enough to normalize it with .strip().lower() and check for stop; convert only actual scores with int(...) and append them to scores.
After the loop, print only the list. Use input() without a visible prompt. You may assume every input other than the stopping command is a valid whole number.
For these inputs:
1025-3stopthe output must be:
[10, 25, -3]If the first input is stop, print [].
A Numeric Sentinel
A reserved number can also signal the end of input. When input is guaranteed to be numeric, convert it first and then compare the number with the sentinel:
distances = []
while True: distance = float(input("Distance (-1 to stop): "))
if distance == -1: break
distances.append(distance)Because the comparison happens after conversion, -1 and -1.0 represent the same numeric sentinel. The reserved value cannot also be used as data, and it must still be checked before appending.
Collect First, Process Afterwards
After the collection loop ends, there is a completed list to process. That suggests two loops with different jobs:
- a
while Trueloop collects an amount of input that is not known in advance; - a
forloop later visits each item in the completed list once.
Before collection, you do not know how many values the user will enter. Once it ends, you can process the completed list without asking for more input.
Summarizing Collected Data
Suppose the earlier loop has finished collecting lap_times. A separate loop can calculate their total:
total_time = 0
for lap_time in lap_times: total_time = total_time + lap_time
print(f"Number of laps: {len(lap_times)}")print(f"Total time: {total_time}")If the user stopped immediately, lap_times is empty. The for loop then runs zero times, so total_time remains 0. A program should handle this case deliberately unless its task guarantees at least one item.
Summarize reading sessions
0 / 20 points
Write a program that reads the number of pages completed in an unknown number of reading sessions. Each page count is a whole number on its own input line. The word done ends data entry.
The stopping command is case insensitive and may have whitespace around it: done, Done, and DONE all end input. The command is not a page count and must not be stored.
Keep the work in two phases: first collect the page counts in a list, then calculate their total after input ends. Write a loop for each phase and calculate the total yourself; do not use sum(...).
Use input() without a visible prompt. Print exactly these two lines:
Sessions: 3Total pages: 47The example output is for page counts 12, 20, and 15 followed by done. If the first input is done, print zero sessions and zero total pages. You may assume every other input is a valid whole number.
What break Skips
break skips the rest of its current loop body as well as all later iterations:
while True: action = input("Action: ").strip().lower()
if action == "exit": break
print(f"Accepted: {action}")
print("Goodbye.")For the stopping input, the Accepted line does not run. The Goodbye line does run because it is after the loop. Trace statements in execution order: indentation shows whether a statement is inside or after the loop.
In the next questions, trace how statement order affects what happens on the stopping iteration.
Python allows many conditions after while. In this part, you will mainly use while True with break when the input says to stop.
The loop can keep asking for input without knowing how many values the user will provide.
Check Your Understanding
- Why does
while Trueneed some reachable way to executebreak? - Why is the sentinel normally checked before
.append(...)? - Why must a word sentinel be checked before converting numeric data?
- Why is a
forloop often a good choice after collection finishes? - What happens when the user enters the sentinel on the first iteration?
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.