All lessons

Lists & loops · step 14 of 22

While loops & loop control

10 minRepeat until something changes, and know how to break out.

While something stays true

A while loop repeats for as long as its condition is true. You are responsible for changing something inside, or it never ends.

count = 1
while count <= 3:
    print(count)
    count = count + 1     # or count += 1
print("Done")

for or while?

Use for when you know the items or how many times. Use while when you are waiting for a condition — until a total passes a limit, until the value reaches zero.

break and continue

break leaves the loop immediately; continue skips the rest of this round and starts the next.

number = 0
while True:
    number += 1
    if number == 4:
        break
print(number)     # 4

If a loop never ends, the tab freezes — always check that the value your condition tests actually changes. The code practice here runs in a sandbox with a time limit for exactly that reason.

Remember this

  • while repeats until its condition is false
  • Change the tested value inside the loop or it never ends
  • break exits the loop, continue skips to the next round

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. What must happen inside a while loop?

  2. 2. What does break do?

  3. 3. count = 1 with `while count <= 3` — how many times does the block run?

Answer all three to check them.

Now write it yourself

0/2 passed
1

Practice 1

Print the numbers 1 to 5 with a while loop, one per line.

practice_1.py
2

Practice 2

Start at 10 and count down by 3 while the value stays above 0, printing each value.

practice_2.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.