Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 6-8

While Loop

A control structure that repeats a block of code as long as a specified condition remains true.


Quick Answer

A control structure that repeats a block of code as long as a specified condition remains true. Use it when you do not know in advance how many repetitions you need: keep asking for a password while it is wrong, keep a game running while the player has lives, keep doubling a number while it is under 1,000. The condition is tested before every pass, including the first, so if it starts false the body never runs, and something inside the body must eventually make it false.

Why This Matters

A while loop lets a program respond to what actually happens instead of a count fixed in advance: retry a download until it succeeds, read input until the user types quit, keep a robot driving until its sensor sees a wall. Forget to change the condition inside the loop and the program never stops, which is how an app freezes; write < where you meant <= and it stops one pass early.

Intuitive Explanation

Picture filling a water bottle at a tap. Before each pour you look: is it full yet? If not, pour a little and look again. If the bottle was already full when you picked it up, you never pour at all. A while loop is exactly that cycle: test, run the body, test again, and leave the moment the test says false.

Trace count = 0 followed by while count < 3: print(count), then count = count + 1. Test 0 < 3, true: print 0, count becomes 1. Test 1 < 3: print 1, count becomes 2. Test 2 < 3: print 2, count becomes 3. Test 3 < 3, false: leave. That is three passes printing 0, 1 and 2, and four tests, because the last test is the one that fails. The line count = count + 1 is what moves the loop toward its end; delete it and the test 0 < 3 stays true forever.

When the number of passes is known before the loop starts, such as printing the numbers 1 to 10 or visiting every name in a list, a for loop states that count directly and updates the variable for you. A while loop is the right fit when the stopping point depends on something that happens during the loop: a correct password, a balance reaching a goal, a number crossing a limit.

Think of it like this. Stirring a sauce until it thickens is a while loop: check whether it has thickened, stir if not, check again, and stop the moment it has. If it was already thick, you would not stir once. The comparison breaks in one place: a cook eventually gives up, but a loop whose condition never changes keeps going forever.

Core idea. While loops check the condition before each iteration. If the condition is false from the start, the body never executes.


When to Use

Use a while loop when repetition should go on until something happens and you cannot count the passes in advance: keep asking until the input is valid, keep playing as long as lives remain, keep saving until a goal is reached. It needs three parts: a variable set before the loop, a condition that tests it, and a change inside the body that moves the test toward false. If you know the number of repetitions, or you are visiting every item in a list, use a for loop instead.

Tip. Ask: Must the steps repeat until a condition changes, with the number of passes unknown before the loop starts?

How to Recognize It

Before choosing a loop, ask what makes the repeating stop and whether the number of passes could be known in advance.

  1. Does the repeating stop because something happens, such as a correct guess or a full bottle, rather than after a set count?

    Yes means a while loop. If you can list the items or the count before starting, a For Loop is simpler.

  2. Could the condition already be false the first time it is checked?

    Yes means the body may run zero times, which is correct for a while loop; plan for it, as when a password is right on the first try and the retry loop never runs.

  3. Does a line inside the body change the variable the condition tests?

    Yes means the loop can end. No means an infinite loop: while lives > 0 never stops if no line ever lowers lives.

  4. Should the steps run at most once, only if the condition is true?

    Yes means you want Selection, an if statement, not a loop. A while keeps repeating its body for as long as the condition stays true.

While Loop vs For Loop vs Selection vs Iteration

Each of these decides whether code runs again, so beginners swap them. Ask what ends the repeating: a condition you cannot predict, the end of a known list, nothing because it runs once, or whether you mean repeating in general.

While Loop

Meaning
A while loop checks a condition before each pass and keeps running its body for as long as that condition stays true.
Key test
Stops when a condition changes; the number of passes is unknown in advance.
Example
while guess != secret: guess = int(input('Try again: ')) keeps asking until the guess is right.

For Loop

Meaning
A for loop runs its body once for each value in a range or each item in a collection.
Key test
The items or the count are known before the first pass.
Example
for name in ['Ana', 'Ben', 'Cy']: print(name) runs exactly three times.

Selection

Meaning
Selection, an if statement, checks a condition once and runs its block at most one time.
Key test
Runs zero times or once, and never repeats.
Example
if score > best: best = score updates the record once, if at all.

Iteration

Meaning
Iteration is the general idea of repeating steps, and while loops and for loops are two ways to write it.
Key test
The idea of repeating, before you choose which loop to write.
Example
'Keep stirring until thick' and 'stir 20 times' are both iteration; one becomes a while, the other a for.

Formula & Notation

Worked Examples

Example 1 — Trace the loop by hand

Standard

n starts at 3, and while n is less than 20 the program doubles it. Count how many times the body runs, and give the value printed at the end.
Show the steps and the answer
  1. First visit to the diamond n < 20?: 3 < 20 is true, so take the yes branch and double, n = 6.

    In this flowchart the test comes before the body, so even the first doubling has to be earned by a true test.

  2. Follow the arrow back to the diamond: 6 < 20 is true, n = 12. Back again: 12 < 20 is true, n = 24.

    After every pass the arrow returns to the same test before anything else happens.

  3. Next test: 24 < 20 is false, so take the no branch to OUTPUT n, which prints 24.

    The only exit is the no branch, and control reaches it only after n has already gone past 20.

  4. Tally: 3 passes (to 6, 12 and 24) and 4 tests, the last one false.

    A while loop always ends on a failed test, so it makes one more test than it has passes.

Answer: The body runs 3 times (3 → 6 → 12 → 24) and the program prints 24.

Takeaway: Keep two tallies when tracing a while loop, passes and tests; the value printed is the first one to fail the test, which is why it is above 20.

Example 2 — Zero passes, and where it stops

Standard

A savings program sets weeks = 0, then while balance < 40 it adds 15 to balance and 1 to weeks. Find weeks when balance starts at (a) 10 and (b) 50.
Show the steps and the answer
  1. (a) Test 10 < 40, true: balance 25, weeks 1. Test 25 < 40, true: balance 40, weeks 2.

    Each pass adds one week's savings, then control returns to the test.

  2. Test 40 < 40: false, so the loop stops with weeks = 2.

    Reaching exactly 40 meets the goal, and < stops the loop there; with <= it would run an unneeded third week.

  3. (b) Test 50 < 40: false before any pass, so the body never runs and weeks stays 0.

    The test comes first, so a goal that is already met costs zero weeks.

  4. Compare a for loop fixed at 3 passes: it would report 3 weeks in both cases.

    When the stopping point depends on the data, a fixed count gives wrong answers, which is the signal to use while.

Answer: (a) weeks = 2, ending at a balance of 40; (b) weeks = 0, because the test fails before the first pass.

Takeaway: A while loop can run zero times, and the comparison sign decides whether reaching the goal exactly stops it.

Example 3 — Find the mistake: a countdown that never ends

Application

A countdown should print 5, 4, 3, 2, 1 and then Liftoff. Ava writes t = 5, then while t > 0: print(t), then print('Liftoff') after the loop. The program prints 5 over and over and never reaches Liftoff. Find the mistake and correct it.
Show the steps and the answer
  1. Trace: t = 5, test 5 > 0 is true, print 5, and return to the test with t still 5.

    Nothing in the body changes t, so every test sees the same value.

  2. 5 > 0 is true on every pass, so the loop never ends.

    A while loop stops only when its condition becomes false, and no line here can make it false.

  3. Add t = t - 1 inside the body, after print(t).

    Each pass now moves t one step closer to 0, the value that ends the loop.

  4. Retrace: prints 5, 4, 3, 2, 1; then t = 0, the test 0 > 0 is false, and Liftoff prints.

    Five passes and a sixth, failing test give exactly the countdown wanted.

Answer: Add t = t - 1 inside the loop body. The program then prints 5, 4, 3, 2, 1, Liftoff.

Takeaway: Every while loop needs a line in its body that moves the condition toward false; look for it before you run the code.

Where You'll See It

  • Entering a password

    Keep asking for the password WHILE it's still wrong — you don't know how many tries it'll take, so the loop repeats until the condition becomes false.

  • Filling a water bottle

    Keep pouring WHILE the bottle isn't full; the moment it's full the condition is false and you stop — and if it was already full you never pour at all.

  • A game's main loop

    WHILE the player still has lives, keep running the round; once lives hit 0 the condition fails and the game ends.

Common Mistakes

  1. The slip: A while loop always runs at least once.

    Why it's tempting: It's a loop, so it feels like it must execute the body before it can decide to stop.

    Instead: A while checks its condition before each iteration; if the condition is false from the start, the body runs zero times.

  2. The slip: If I just write the condition, the loop will eventually stop on its own.

    Why it's tempting: The condition mentions the variable, so it seems like the loop manages it.

    Instead: You must change something inside the body that moves the condition toward false; forgetting to update it creates an infinite loop.

  3. The slip: while x < 10 and while x <= 10 behave the same.

    Why it's tempting: Both look like 'loop until about 10', a tiny difference that seems harmless.

    Instead: < stops when x reaches 10; <= runs one extra time at x = 10. Picking the wrong one is a classic off-by-one error.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. i = 1; while i <= 4: print(i * 10); i = i + 1. What prints, and how many times does the body run?

    Hint: Check the condition before each run of the body.

  2. n = 50; while n > 0: n = n - 15. How many times does the body run, and what is n at the end?

    Hint: Write down n after each pass and check n > 0 each time.

  3. total = 0; k = 1; while total < 20: total = total + k; k = k + 1. What are total and k when the loop ends?

    Hint: Make a table of total and k after each pass.

  4. x = 10; while x < 5: x = x + 1. How many times does the body run, and what is x afterwards?

    Hint: Check the condition before the first pass.

  5. You want to keep asking for a password until the user types it correctly. Should you use a while loop or a for loop?

    Hint: Do you know in advance how many tries it will take?

  6. count = 5; while count > 0: print(count). A student says: 'This prints 5, 4, 3, 2, 1.' What actually happens, and what is missing?

    Hint: Does anything inside the loop change count?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

How do I stop a while loop from the middle?

Use break: it ends the loop at once, and the program carries on after it. A common shape is while True: with a break inside, used when the stopping test only makes sense partway through a pass, such as after reading what the user typed. The loop condition itself is never false, so a missing break means an infinite loop. If a program is stuck in one, pressing Ctrl+C in most terminals stops it.

How do I keep asking until the user types something valid?

Ask once before the loop, then keep asking while the answer is not acceptable: age = input('Age? '), then while not age.isdigit(): age = input('Please type a number: '). The body runs only if the first answer was bad, and the loop ends the moment a good one arrives. This ask-until-valid shape is one of the most common jobs a while loop does.

Can a while condition test two things at once?

Yes. while lives > 0 and not won: keeps a game going only while both parts are true, so it stops as soon as the lives run out or the player wins, whichever comes first. With or, the loop continues while either part is true. After such a loop ends, check which part turned false, such as if won:, because the program usually needs to do something different in each case.

Why does my loop that adds 0.1 each time never stop?

Decimal steps are not stored exactly. Adding 0.1 ten times gives 0.9999999999999999 in Python, not 1, so a loop written as while x != 1: steps straight past 1 and runs forever. Test with < instead, as in while x < 1:, so the loop ends once x reaches or passes the target. Counting in whole numbers and dividing by 10 only when you need the decimal is safer still.

Learning Path

← Before

Iteration
While Loop

You are here

Next →

For Loop
You need Iteration (the idea of repeating a block of steps) first. The while loop adds repetition controlled by a condition tested before every pass, so the loop can run zero times, a few times or many. Next, the For Loop handles the common case where the number of passes or the collection of items is known, and it updates its loop variable automatically.

See Also