Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 15 min

The while loop

By the end of this chapter, you'll be able to

  • Write a while loop with a stopping condition
  • Choose between for and while depending on the problem
  • Make sure a while loop stops
  • Leave a loop with break

Repeating while…

while repeats its block as long as its condition is True. The condition is checked before each round.

It takes 9 years.

Step 10 of 10
Text description of the animation
  1. We don't know how many years it will take: we'll stop when the savings reach 150.
  2. At the start: €100 and 0 years.
  3. The condition is true: we enter the loop.
  4. After one year: €105. Back to the condition.
  5. After two years: €110.25. Each year, we earn a little more than the year before.
  6. We skip ahead a few rounds: after 7 years, €140.71, still less than 150.
  7. After 8 years: €147.75. One more round!
  8. After 9 years: €155.14.
  9. The condition is false: we leave the loop.
  10. It takes 9 years.
savings = 100
years = 0
while savings < 150:
    savings = round(savings * 1.05, 2)
    years = years + 1
print(years, "years")
print(savings, "€")
9 years
155.14 €

round(x, 2) rounds to two decimal places, like for cents.

for or while?

  • You know the items or the number of rounds: for ("for each student", "10 times").
  • You only know the stopping condition: while ("until it goes over 150", "as long as the answer is wrong").

Leaving early with break

break immediately stops the current loop. It's useful when you're searching for something:

numbers = [7, 12, 5, 30, 8]
for n in numbers:
    if n > 10:
        print("First number greater than 10:", n)
        break
First number greater than 10: 12

Your turn

Mini-lab: the populationPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Worked exercise: the countdown

Write a program that displays a countdown from 5 to 1 with while, then displays "Lift-off!".

Hint 1
Start with n = 5, and keep going while n > 0.
Hint 2
Don't forget to decrease n on each round, otherwise the loop will never stop.
Show the solution and common mistakes
n = 5
while n > 0:
    print(n)
    n = n - 1
print("Lift-off!")
5
4
3
2
1
Lift-off!

Common mistakes:

  • Writing while n >= 0: the countdown also displays 0.
  • Putting print("Lift-off!") inside the block: it would be displayed on every round.

Summary

  1. 1while repeats a block as long as its condition is True.
  2. 2Choose for when you know the items, while when you know the stopping condition.
  3. 3A while loop must change what its condition tests, otherwise it's infinite.
  4. 4break immediately stops the loop.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.