Python · Stage 4 – Repeating Things · Lesson 27 of 50

Common Loop Mistakes

Recognize infinite loops and off-by-one errors before they cause trouble.

count = 1
while count <= 3:
    print(count)
Line-by-line explanation
  1. Count starts at 1.
  2. The condition remains True.
  3. Nothing changes count.
  4. The loop displays 1 forever. This example is intentionally broken.
for number in range(1, 4):
    print(number)
Line-by-line explanation
  1. range(1, 4) produces 1, 2, and 3.
  2. The ending value 4 is not included.
  3. The loop displays exactly three numbers.

If a program is stuck in a terminal, Ctrl + C usually asks it to stop.

Tiny Practice

Fix the loop so it displays 1, 2, and 3, then stops.

Starter template

count = 1
while count <= 3:
    print(count)
    CHANGE_ME
Line-by-line explanation
  1. The condition is correct.
  2. The counter must change.
Hint
  1. Assign a new value to count.
  2. Add 1 to its current value.
  3. Keep the line inside the loop.
Show Solution
count = 1
while count <= 3:
    print(count)
    count = count + 1
Line-by-line explanation
  1. Count begins at 1.
  2. Each iteration displays it.
  3. The increment eventually makes the condition False.