Find a course

Module 3: Decisions and LoopsLesson 7 of 1212 min

Repeating With while Loops

Repeat code while a condition holds, avoid infinite loops, validate input with while True and break, and use loops to answer how-long questions.

Step 1 of 14Learn

Doing something again and again

Computers are tireless at repetition, and loops are how you ask for it. A while loop repeats a block as long as its condition is true:

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

Output: 3, 2, 1, Liftoff!

Python checks the condition, runs the indented block if it's true, then jumps back to the top and checks again. When the condition becomes false, the loop ends and execution continues with the first unindented line after it. Each pass through the block is called an iteration.

If the condition is false from the start, the block runs zero times. Set count = 0 above and the program prints only "Liftoff!".

A while loop fits situations where you don't know in advance how many repetitions you need:

  • Keep asking until the user enters a valid number.
  • Keep doubling an investment until it passes a target.
  • Keep reading lines until the file runs out.
  • Keep a game running until the player quits.

When you do know the number of repetitions, or you're stepping through a collection, a for loop (next lesson) is usually cleaner.

Step 2 of 14Learn

Anatomy of a loop, and how loops go wrong

Most while loops have three parts:

  1. Initialize a variable before the loop: count = 3.
  2. Test it in the condition: while count > 0:.
  3. Update it inside the loop: count = count - 1 (or count -= 1).

Forget the update, and the condition never changes. The result is an infinite loop: the program prints 3 forever, or simply appears frozen. It happens to everyone. Press Ctrl+C in the terminal to stop it (or the Stop button in your editor), then look for the missing or wrong update.

Other classic loop bugs:

  • Updating in the wrong direction: count += 1 in a countdown that tests count > 0 runs forever.
  • Off by one: while count >= 0 also prints 0, one more iteration than intended. When a loop's count matters, trace the first and last iterations on paper.
  • Updating outside the block: if the update line isn't indented, it runs only after the loop, which, with an unchanging condition, is never.

A good habit when writing any loop is to ask two questions: What makes this condition become false? and Does every iteration move toward that? If you can't answer both, the loop may never end.

Step 3 of 14Practice · Diagram

One trip around a while loop

Which part is missing in most infinite loops?

Tap the shape that answers the question, then press Check.

One trip around a while loopCycle diagram: Test: count > 0? → Run body: print(count) → Update: count -= 1.count = 3(initialize)Test: count >0?Run body:print(count)Update: count-= 1
Test: count > 0?

If False, leave the loop and continue after it.

Run body: print(count)
Update: count -= 1

Forget this and the test never becomes False: an infinite loop.

Step 4 of 14Practice · What would you do?

What would you do?

How many times does this loop print "Saving"?

balance = 100
while balance < 150:
    print("Saving")
    balance = balance + 20

Step 5 of 14Learn

while True, break and continue

Sometimes the natural place to decide whether to stop is in the middle of the loop, not at the top. The common pattern is an intentionally endless loop with an exit inside:

while True:
    text = input("Enter your age: ").strip()
    if text.isdigit():
        age = int(text)
        break                  # leave the loop immediately
    print("Please type a whole number.")
print(f"Thanks! You are {age}.")
  • break exits the loop immediately; Python continues after the loop.
  • continue skips the rest of the current iteration and jumps back to the condition check.
n = 0
while n < 10:
    n += 1
    if n % 3 == 0:
        continue           # skip multiples of 3
    print(n)               # 1 2 4 5 7 8 10

while True with break is the standard way to validate input: keep asking until the answer is acceptable. It's also how menus and simple games run: loop forever, show options, and break when the user chooses Quit.

Use break and continue sparingly. One clear exit is easy to follow; five scattered ones make a loop hard to reason about. With nested loops, remember that break exits only the innermost loop it's in.

Step 6 of 14Practice · Work it out

Starting with n = 1, a while loop runs n = n * 2 for as long as n < 100. What is the value of n after the loop ends?

Step 7 of 14Learn

Loops that answer "how long until…?"

A while loop is the natural tool for questions like "how many years until my savings double?" because you don't know the answer in advance; you simulate year by year until a condition is met:

balance = 1000.0
rate = 0.07
years = 0
while balance < 2000:
    balance = balance * (1 + rate)
    years += 1
print(f"{years} years, balance {balance:.2f}")
# 11 years, balance 2104.85

The variable balance is an accumulator: it carries a running value from one iteration to the next. years is a counter. Together they turn a question that needs algebra (or the Rule of 72, which estimates 72 / 7 ≈ 10.3 years) into a few lines anyone can follow and modify: add a yearly deposit, change the rate halfway through, or stop at a target date.

Simulation like this is one of programming's superpowers. Real systems are full of rules that are easy to describe step by step but hard to solve with a single formula: loan payoffs with extra payments, inventory that is restocked when it drops below a threshold, populations that grow and decline. Write the rule for one step inside a loop, and let the computer repeat it.

Step 8 of 14Practice · Chart

The savings loop, year by year ($1,000 at 7%)

Tap the year when the condition balance < 2000 first becomes False.

Tap the point that answers the question, then press Check.

The savings loop, year by year ($1,000 at 7%)Line chart with 12 categories: 0: balance $1,000, target $2,000; 1: balance $1,070, target $2,000; 2: balance $1,145, target $2,000; 3: balance $1,225, target $2,000; 4: balance $1,311, target $2,000; 5: balance $1,403, target $2,000; 6: balance $1,501, target $2,000; 7: balance $1,606, target $2,000; 8: balance $1,718, target $2,000; 9: balance $1,838, target $2,000; 10: balance $1,967, target $2,000; 11: balance $2,105, target $2,000.$1,000$1,250$1,500$1,750$2,000$2,25001234567891011years (loop iterations)
Each point is one pass through the while loop above.
The savings loop, year by year ($1,000 at 7%)
years (loop iterations)balancetarget
0$1,000$2,000
1$1,070$2,000
2$1,145$2,000
3$1,225$2,000
4$1,311$2,000
5$1,403$2,000
6$1,501$2,000
7$1,606$2,000
8$1,718$2,000
9$1,838$2,000
10$1,967$2,000
11$2,105$2,000

Step 9 of 14Practice · Code challenge · Python

Complete years_to_double(balance, rate) so it returns how many whole years it takes for balance to reach at least double its starting value when it grows by rate each year (0.07 means 7%). Use a while loop.

Real Python, running in a sandbox in your browser.
  • years_to_double(1000, 0.07)
  • years_to_double(1000, 0.1)
  • years_to_double(500, 1.0)
  • years_to_double(200, 0.25)

Step 10 of 14Try the calculator

Years until a target (what the loop computes)

This calculator gives the same answer as the while loop above: the number of whole years before the balance reaches the target.

Years the loop runs
11 years
Balance when the loop stops
2,104.85 $
Rule of 72 estimate for doubling
10.3 years

Step 11 of 14Note

Step 12 of 14Practice · True or false

In a while loop, continue ends the loop completely and moves on to the code after it.

Step 13 of 14Practice · Match the pairs

Match each piece of loop syntax to what it does.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. break
  2. continue
  3. while True:
  4. Ctrl+C
  5. count += 1

Step 14 of 14Practice · Choose one

With count = 0 set first, the one-line loop while count < 5: print(count) never stops. What fix makes it print 0 to 4 and end?