Codiqo

Learn Python · lesson 17 of 60 · about 8 minutes

while Loops and break

Write Sam's savings plan out week by week: repeat code while a condition stays True, and stop the loop early with break.

What you'll learn

  • Write a while loop
  • Make sure the loop ends
  • Exit early with break

Week by week

The assistant already says how many full weeks the bike will take, but Sam wants the plan written out: Week 1: 60 saved, Week 2: 75 saved, and so on until there's enough. Nobody knows how many lines that is until the adding is done, and that's exactly the job of a while loop.

Repeat while something is True

A while loop checks its condition, runs its block, then checks again, over and over until the condition is False.

Something inside the loop must change, or the condition stays True forever. That's an infinite loop.

Counting down

count = 3
while count > 0:
    print(count)
    count -= 1
print("Lift off!")

Output

3
2
1
Lift off!

Step through it to watch the plan grow

plan = 90
week = 0
while plan < 120:
    week += 1
    plan += 15
    print(f"Week {week}: {plan} saved")

Output

Week 1: 105 saved
Week 2: 120 saved

Leaving early with break

break jumps straight out of the loop, even if the condition is still True. It's handy when you find what you're looking for.

Stop at the first multiple of 7

n = 20
while n < 100:
    if n % 7 == 0:
        print(f"Found {n}")
        break
    n += 1

Output

Found 21

A limit for a long plan

Starting from nothing, the plan would take 8 weeks, and a smaller weekly amount could take months. Sam only wants to see the next 6 weeks. So the loop checks the week first, and once 6 weeks are on the screen it prints ... and stops with break.

Tip

If a program seems frozen, it's probably stuck in an infinite loop. Check that the loop variable changes every time round.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.