While Loops and Range
Learning Objectives
- You can write a
whileloop. - You can use
breakto exit a loop. - You can use
range()withforto run a loop a fixed number of times. - You can recognize an infinite loop and explain how to prevent it.
The for item in list loop is the most common loop in this course, but it is not the only one. Two other shapes come up regularly:
whileloops for when you do not know in advance how many times the loop should run — for example, “keep asking until the user is done”.range()for when you want to run a loop a fixed number of times — for example, “do this five times”.
This chapter introduces both.
The Classic Input Loop
A while loop keeps running as long as a condition is true.
The most common reason to write a while loop is to keep asking the user for input until they signal that they are done. The pattern looks like this:
while True: subject = input("Subject (or 'done' to quit): ") if subject == "done": break print(f"Logged {subject}.")
print("All done.")while True: is a loop that, on its own, would run forever — the condition is always true. The way out is the break statement, which immediately exits the surrounding loop. So this loop runs until the user types done, at which point break jumps out and the program continues with All done.
Read this loop carefully, because the study log in this part’s project uses exactly this shape. The pattern is:
- Loop forever.
- Ask the user for input.
- If the input is the “quit” signal,
breakout. - Otherwise, process the input.
This is sometimes called a sentinel loop — "done" is the sentinel value that means “stop”. Common sentinels include "done", "quit", an empty input, or sometimes 0 or -1 for numeric programs.
An alternative shape is
quit = Falseoutside the loop, withwhile not quit:andquit = Trueinstead ofbreak. Both work. Thewhile True: ... breakversion is more common in practice because the exit condition lives right next to the input that triggers it, which is easier to read.
Sentinel subject loop
0 / 10 points
Write a program that repeatedly asks for a subject until the user types done.
Normalize the subject with .strip().lower() before checking whether it is done. Store every non-quit subject in a list. After the loop, print how many subjects were logged.
Example input:
MathArtDoneRequired output text:
Subjects logged: 2If the first input is done, the required output is:
Subjects logged: 0Infinite Loops
A while True: loop that does not have a break in the body runs forever or that never encounters a break statement.
If you run a program with an infinite loop in the sandbox, it will keep producing output forever or stop responding. You can usually stop it with a button labeled “stop” or “interrupt”. Then read your loop and find the part that should have changed the condition.
An infinite loop is not a bug in Python or in the sandbox. It is a bug in your code. The fact that the program ran forever is the symptom; the cause is somewhere in the body.
Choosing the loop shape
0 / 5 points
Which situation is the best fit for while True with a break?
range() for “Do This N Times”
Sometimes you want a loop to run a fixed number of times, and you do not have a list to loop over. The range() function generates a sequence of integers for exactly this case.
for i in range(5): print(f"Iteration {i}")This prints:
Iteration 0Iteration 1Iteration 2Iteration 3Iteration 4range(5) produces the numbers 0, 1, 2, 3, 4 — five values, starting from 0. The loop variable i (a common name for an iteration counter) takes each one in turn.
Notice that the sequence stops before 5. This matches the indexing convention from strings and lists: indexes start at 0, and range(n) gives you exactly the valid indexes for a sequence of length n. That is not a coincidence — it makes it easy to loop over a list by index when you need to:
subjects = ["Math", "Physics", "Linear Algebra"]for i in range(len(subjects)): print(f"{i}: {subjects[i]}")This prints:
0: Math1: Physics2: Linear AlgebraIn most cases, for subject in subjects: is more readable than for i in range(len(subjects)):. Use the index version only when you actually need the index for something — for example, when you need to print the position alongside the item.
Numbered subjects
0 / 10 points
Start with this list:
subjects = ["Art", "Math", "History"]Do not ask the user for input in this exercise.
Use range(len(subjects)) to print each index and subject in this exact format: <index>: <subject>.
Example input:
(no input)Required output text:
0: Art1: Math2: HistoryWhen to Use while vs for
A useful rule of thumb:
- Use
forwhen you know what you are iterating over: a list, a string, arange. The loop will run a predictable number of times. - Use
whilewhen you do not know in advance how many times the loop should run, and the exit condition depends on something that happens inside the body.
The classic “ask until done” pattern is squarely a while True: ... break job. The classic “do something with every item in this list” pattern is squarely a for job. Most loops you write this part will be one of these two shapes.
Print a range of numbers
0 / 10 points
Ask the user for a number. Convert the input to an integer.
Use range() and a for loop to print the numbers from 0 up to, but not including, the user’s number. Print each number on its own line.
Example input:
4Required output text:
0123Common Pitfalls
A short list of common mistakes:
- Forgetting to update the loop variable. The classic
whileinfinite loop. The condition needs something to change, or it never becomes false. while True:with nobreak. Also infinite. The exit has to live somewhere in the body.- Off-by-one with
range(1, 10). This produces1through9, not1through10. The stop value is excluded. while count < 5when you meantwhile count <= 5. Same off-by-one but inwhileform. Always ask: what is the last value at which I want the loop to run, and what does that imply about the condition?
Check Your Understanding
- Why does this loop never end?
count = 5while True: print(count)- How many numbers does
range(0, 10)produce, and what is the last one? - Rewrite the following
whileloop usingforandrange:
i = 0while True: if i >= 5: break
print(i) i += 1AI 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.