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

while Loops

Repeat a block while one condition remains True.

count = 1
while count <= 3:
    print(count)
    count = count + 1
Line-by-line explanation
  1. The counter starts at 1.
  2. The loop continues while count is at most 3.
  3. The current number is displayed.
  4. The final line increases count so the loop can eventually stop.

Tiny Practice

Make the loop display 1 and 2, then stop.

Starter template

count = 1
while CHANGE_ME:
    print(count)
    count = count + 1
Line-by-line explanation
  1. The counter starts at 1.
  2. It increases after every display.
Hint
  1. Continue while count is at most 2.
  2. Use <=.
  3. Keep the increment.
Show Solution
count = 1
while count <= 2:
    print(count)
    count = count + 1
Line-by-line explanation
  1. Count begins at 1.
  2. The condition allows 1 and 2.
  3. After count becomes 3, the loop stops.