Making Decisions and Repeating Work

While Loops and Range


Learning Objectives

  • You can write a while loop.
  • You can use break to exit a loop.
  • You can use range() with for to 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:

  • while loops 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:

  1. Loop forever.
  2. Ask the user for input.
  3. If the input is the “quit” signal, break out.
  4. 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 = False outside the loop, with while not quit: and quit = True instead of break. Both work. The while True: ... break version 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:

Math
Art
Done

Required output text:

Subjects logged: 2

If the first input is done, the required output is:

Subjects logged: 0

Infinite 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 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

range(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: Math
1: Physics
2: Linear Algebra

In 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: Art
1: Math
2: History

When to Use while vs for

A useful rule of thumb:

  • Use for when you know what you are iterating over: a list, a string, a range. The loop will run a predictable number of times.
  • Use while when 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:

4

Required output text:

0
1
2
3

Common Pitfalls

A short list of common mistakes:

  • Forgetting to update the loop variable. The classic while infinite loop. The condition needs something to change, or it never becomes false.
  • while True: with no break. Also infinite. The exit has to live somewhere in the body.
  • Off-by-one with range(1, 10). This produces 1 through 9, not 1 through 10. The stop value is excluded.
  • while count < 5 when you meant while count <= 5. Same off-by-one but in while form. 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

  1. Why does this loop never end?
count = 5
while True:
print(count)
  1. How many numbers does range(0, 10) produce, and what is the last one?
  2. Rewrite the following while loop using for and range:
i = 0
while True:
if i >= 5:
break
print(i)
i += 1

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