Skip to contentSkip to navigation

Module 02 · Lesson 05

Indefinite Loops & Loop Control

Repeat until something changes with while loops, avoid infinite loops, leave a loop early with break, skip an item with continue, and use the loop else clause.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Loop until done
  • Leave early with break
  • Skip with continue
  • Watch a loop break out

Repeat until something changes

A `while` loop keeps going as long as its condition is `True`. You do not need to know how many rounds in advance.

  • while

    while fuel > 0: checks the question, runs the block, then checks again.

  • Three parts

    A start value before the loop, a check at the top and a change inside. Forget the change and it never stops.

  • break

    break leaves the loop straight away, even if the condition is still True.

  • continue

    continue skips the rest of this round and jumps back up to the check.

Loops that wait

Many programs repeat until something happens, not a set number of times.

  • Game loopsWhile the player has not quit: read the keys, move everything, draw the screen.
  • MicrowavesWhile time is left: wait a second and take one away. At 0, beep.
  • DownloadsWhile the file is not finished: fetch the next piece and grow the progress bar.
  • AlarmsWhile nobody presses stop: ring again every few minutes.

The first line of a while loop

It looks like an `if`, but it keeps asking. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

keyword:while asks its question at the start of every round, not just once like if.

Loop until done

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Count down

Start, check, change: the three parts every counting loop needs.

Your turn: Make it count down from 10 in twos.

Python
n = 5
while n > 0:
    print(n)
    n -= 1
print("Go!")
Output
Press Run to see what it prints.

Watch a loop break out

Press Step to run one line at a time. Watch the check at the top, and what `break` does.

Ready. Press Step to run the first line.

  1. coins = 0
  2. while coins < 20:
  3. coins += 4
  4. if coins == 12:
  5. break
  6. print("Coins:", coins)
  7. print("Stopped at", coins)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Where does it stop?

n = 10
while n > 0:
    n -= 3
print(n)

0 of 6 answered

Common while loop misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Repeating until something changes

A while loop checks a condition, runs its block if the condition is true, and then checks again. It repeats until the condition is false.

Try it 1: edit me, then Run
count = 1
while count <= 3:
    print("Round", count)
    count += 1
print("Finished")
Output
Press Run to see what it prints.

Step by step: count is 1, the condition 1 <= 3 is true, so the block prints Round 1 and makes count 2. Python goes back to the while line and checks again. After the third round count is 4, the condition is false, and the program continues with Finished. The condition is checked before each iteration, so if it is false at the start, the block never runs at all.

Every while loop needs three parts

A working while loop almost always has:

  1. a variable set up before the loop,
  2. a condition that uses it,
  3. a line inside the loop that changes it, so the condition can eventually become false.

Forget the third part and you get an infinite loop: the condition stays true forever and the program never moves on. On this site the runner stops a program that runs too long, and you can press Stop at any time. In a terminal on your own computer, Ctrl+C stops it.

Try it 2: edit me, then Run
# Infinite: count never changes
count = 1
while count <= 3:
    print(count)
Output
Press Run to see what it prints.

The other classic mistake is the off-by-one error, where the loop runs one time too many or too few. while count < 3 with count starting at 1 runs twice, not three times. When a loop is off by one, check the starting value and whether the condition uses < or <=.

When to use while instead of for

Use a for loop when you know what you are looping over: every item in a list, or a number of repetitions. Use a while loop when you are repeating until something happens and cannot know in advance how many times that will take.

Try it 3: edit me, then Run
balance = 100
years = 0
while balance < 200:
    balance = balance * 1.07
    years += 1
print(f"Doubled after {years} years: {balance:.2f}")
Output
Press Run to see what it prints.

Nobody tells you the number of years up front; the loop discovers it. This prints Doubled after 11 years: 210.49.

Leaving early with break

break ends the loop immediately, wherever it appears in the block. Python jumps to the first line after the loop. It works in both while and for loops, and is the natural way to stop as soon as you have found what you were looking for.

Try it 4: edit me, then Run
for n in range(2, 50):
    if n % 7 == 0:
        print("First multiple of 7:", n)
        break
Output
Press Run to see what it prints.

Without break, the loop would carry on and print every multiple of 7. With it, the loop stops at 7.

A common pattern is while True: with a break inside. The condition is always true, so the only way out is the break. It is useful when the decision to stop comes in the middle of the block, such as after reading an answer:

Try it 5: edit me, then Run
while True:
    answer = input("Type yes to continue: ")
    if answer == "yes":
        break
    print("Please type yes")
Output
Press Run to see what it prints.

Skipping with continue

continue skips the rest of the current iteration and goes straight to the next one. In a while loop, be careful: if the line that updates the variable comes after the continue, it is skipped too, and the loop never ends. Update first, then continue.

Try it 6: edit me, then Run
for n in range(1, 8):
    if n % 3 == 0:
        continue
    print(n, end=" ")
Output
Press Run to see what it prints.

This prints 1 2 4 5 7: the multiples of 3 are skipped. continue is handy for ignoring blank lines or invalid values, so the main work in the loop does not need to sit inside an extra if.

The else clause on a loop

A loop can have an else block. It runs once when the loop ends normally, because the condition became false or the items ran out. It does not run when the loop ends with break. That makes it a neat way to say "searched everything and did not find it".

Try it 7: edit me, then Run
for n in [3, 5, 9]:
    if n % 2 == 0:
        print("Found an even number")
        break
else:
    print("No even numbers")
Output
Press Run to see what it prints.

Here no break happens, so the else runs and prints No even numbers. Loop else is not common, and many programmers use a flag variable instead, but you should recognise it when you see it.

Keep loops easy to follow

Prefer a clear condition over a loop full of breaks. One break for "found it" or "user wants to stop" is easy to read; five scattered breaks are not. If you need pass as a placeholder in a block you have not written yet, it does nothing and keeps the shape valid.

Syntax

The general shape of the statements in this lesson.

syntax.py
while condition:        # checked before every iteration
    ...
    update              # change something, or it never ends
while True:
    if done:
        break           # leave the loop now
    continue            # skip to the next iteration
else:                   # runs only if no break happened
    ...
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Saving up for a bike

Beginner

Start with 15 in savings and add 12 each week. Work out how many weeks it takes to reach 120, printing the balance each week.

Python
TARGET = 120
savings = 15
weeks = 0
while savings < TARGET:
    savings += 12
    weeks += 1
    print(f"Week {weeks}: {savings}")
print(f"Target reached in {weeks} weeks")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The condition checks the savings before each week. Inside the loop, both variables change, so the condition is guaranteed to become false. The loop runs nine times because after eight weeks the balance is 111, still below the target.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting to update the variable

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
n = 1
while n <= 3:
    print(n)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 1 forever until the program is stopped

Write this instead

n = 1
while n <= 3:
    print(n)
    n += 1

Why it happens

Nothing inside the loop changes n, so n <= 3 stays true.

In the real world

Where this shows up in software people use every day.

  1. A phone battery estimate

    Consumer devices

    A phone estimates how many more hours of video it can play, assuming the battery drops 9 percent an hour and the phone switches off below 5 percent.

    Why Python fits

    The loop does not know the number of hours in advance; it keeps subtracting until another hour would go below the shutdown level. The condition checks the next step before taking it.

    Python
    battery = 64
    hours = 0
    while battery - 9 >= 5:
        battery -= 9
        hours += 1
    print(f"About {hours} hours left, ending at {battery}%")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is while True: bad style?

No, it is common and clear when the exit decision comes in the middle of the loop. Make sure there is a break that will be reached.

Does break leave every loop?

Only the innermost loop it is in. An outer loop keeps going.

My program froze. What happened?

Probably an infinite loop. Press Stop, then check that something inside the loop changes the condition, and that any continue comes after that change.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/5 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.