Session 6 of the Python Fundamentals series, covered in depth. It repeats a block with while, covering the condition that is checked on each pass and the loop variable that must change. It then works through counters and countdowns, the infinite-loop trap, accumulators for running totals and counts, sentinel-controlled loops that stop on a chosen value, flags, and break and continue, and ends with a full guess-the-number game. Every snippet was copied verbatim from CPython 3.12, with interactive input shown as the sequence the user types.
Subject: Python Fundamentals · 101 slides · code lesson
Open the interactive version of this deck · Homework for this lesson
Title
Python Fundamentals - Session 6
Keep going until the program decides to stop
Objectives
A condition decides a branch once. A loop checks a condition over and over - this is where a program can really run. By the end you can:
while loop that repeats a block while a condition stays true.break.continue.Warm-up
Discussion prompt
Before we open Session 6 - while Loops: without looking back, what was the main idea of Session 5 - Comparisons & Logic (and / or / not), and what could you do by the end of it that you could not do before?
Hint: One sentence for the idea, one for the skill. If the second one is blank, that is the part to revisit.
Answer:
That session covers the comparison operators, and, or, and not, truth tables, precedence, range checks, and the x == 1 or 2 trap.
Section
Part 1
Concept
A while loop runs its indented block again and again, as long as its condition is true.
Before each pass it re-checks the condition. The moment the condition is false, the loop ends and the program moves on.
iteration — One pass through the loop body. A loop that runs its block five times has five iterations.
Counterexample
Discussion prompt
A while loop runs its indented block again and again, as long as its condition is true.
That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.
Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.
Answer:
Before each pass it re-checks the condition. The moment the condition is false, the loop ends and the program moves on.
Intuition
Read while i <= 5: as 'keep doing this while i is 5 or less'.
Picture Python at the top of the loop each pass, asking the question again. Yes -> run the body, come back and ask again. No -> leave.
Analogy
Discussion prompt
Explain Repeat-until, out loud by analogy to something with no Python Fundamentals in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.
Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.
Answer:
Read while i <= 5: as 'keep doing this while i is 5 or less'.
Concept
Almost every counting loop has: an initial value before the loop, a condition on the while line, and an update inside that moves toward stopping.
Miss the update and the condition never changes - the loop runs forever.
Explain it
Discussion prompt
Explain The three moving parts to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.
Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.
Answer:
Almost every counting loop has: an initial value before the loop, a condition on the while line, and an update inside that moves toward stopping.
Ranking
Put in order
Put the moves of Count 1 to 5 into the order they have to happen.
Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. The initial value. The condition will be checked against this first.
Worked example
i = 1
while i <= 5:
print(i, end=" ")
i += 1Before the loop: i starts at 1
Why: The initial value. The condition will be checked against this first.
Each pass: print i, then add 1
Why: The body prints, then the update i += 1 nudges i toward the stopping point.
Trace every pass
Why: Verified by execution: prints 1 2 3 4 5. When i becomes 6, 6 <= 5 is False and the loop ends.
| check i <= 5 | i | prints |
|---|---|---|
| True | 1 | 1 |
| True | 2 | 2 |
| True | 3 | 3 |
| True | 4 | 4 |
| True | 5 | 5 |
| False | 6 | stop |
Comparison
Comparison matrix
From Count 1 to 5: refill the i column from what you know. The rest of the table is as it appeared.
| check i <= 5 | i | prints |
|---|---|---|
| True | 1 | 1 |
| True | 2 | 2 |
| True | 3 | 3 |
| True | 4 | 4 |
| True | 5 | 5 |
| False | 6 | stop |
Concept
Something inside the loop has to move the condition toward false - usually the variable the condition tests.
i += 1 each pass is what eventually makes i <= 5 false. Without it, the answer stays 'yes' forever.
Pattern
Predict first
The table runs: True | 3 | T-minus 3 · True | 2 | T-minus 2 · True | 1 | T-minus 1
In A countdown, given the rows so far: what is the next one — the row where check c > 0 is False?
Correct: False | 0 | Liftoff!
| check c > 0 | c | prints |
|---|---|---|
| True | 3 | T-minus 3 |
| True | 2 | T-minus 2 |
| True | 1 | T-minus 1 |
| False | 0 | Liftoff! |
Why: The relationship between the columns, not the individual numbers, is what generates the next row. c starts at 3 and c -= 1 lowers it each pass, heading toward 0.
Worked example
c = 3
while c > 0:
print("T-minus", c)
c -= 1
print("Liftoff!")Count downward this time
Why: c starts at 3 and c -= 1 lowers it each pass, heading toward 0.
The line after the loop runs once, at the end
Why: Verified by execution: T-minus 3, 2, 1, then Liftoff! once c hits 0 and c > 0 is false.
| check c > 0 | c | prints |
|---|---|---|
| True | 3 | T-minus 3 |
| True | 2 | T-minus 2 |
| True | 1 | T-minus 1 |
| False | 0 | Liftoff! |
Trade off
Comparison matrix
From A countdown: every row here is a choice with a cost. Fill the c column, then say which row you would actually pick and what you give up for it.
| check c > 0 | c | prints |
|---|---|---|
| True | 3 | T-minus 3 |
| True | 2 | T-minus 2 |
| True | 1 | T-minus 1 |
| False | 0 | Liftoff! |
Worked example
i = 1
while i <= 5:
print(f"3 x {i} = {3 * i}")
i += 1The body uses i to compute each line
Why: The same block runs five times with i = 1..5, each time filling the f-string.
Trace the outputs
Why: Verified by execution.
| i | prints |
|---|---|
| 1 | 3 x 1 = 3 |
| 2 | 3 x 2 = 6 |
| 3 | 3 x 3 = 9 |
| 4 | 3 x 4 = 12 |
| 5 | 3 x 5 = 15 |
Pattern
Step through it
Step through A multiplication table one row at a time. What is driving the change, and what would the row after the last one be?
Section
Part 2
Concept
If nothing inside the loop can make the condition false, the loop runs forever - an infinite loop.
The program appears to freeze. You usually stop it by pressing Ctrl-C in the terminal.
Anomaly
Predict first
A student writes this, and it looks reasonable:
i stays 1 forever
It is wrong. Say what breaks — and say it before you turn the page.
Correct: There is no i += 1, so i <= 5 is always true.
Update the variable the condition depends on.
Why: There is no i += 1, so i <= 5 is always true. It prints 1 endlessly and never stops on its own.
Trap
The counter never changes.
i = 1
while i <= 5:
print(i)i stays 1 forever
Why: There is no i += 1, so i <= 5 is always true. It prints 1 endlessly and never stops on its own.
| pass | i | condition |
|---|---|---|
| 1 | 1 | True |
| 2 | 1 | True |
| ... | 1 | True (forever) |
Update the variable the condition depends on.
i = 1
while i <= 5:
print(i)
i += 1i += 1 moves toward the exit
Why: Now i climbs 1..5 and the loop ends when i is 6. Real output: 1 through 5, then it stops.
| pass | i | condition |
|---|---|---|
| 1 | 1 | True |
| 5 | 5 | True |
| 6 | 6 | False -> stop |
Error analysis
Annotate
Walk the callouts on Trap: forgetting to update. Each one is a place this is easy to get subtly wrong.
Intuition
Every time through the loop, ask: did this pass bring me closer to the condition becoming false?
If the honest answer is 'no', you have an infinite loop. Counting up toward a limit, or down toward zero, both get closer each pass.
Concept
<= includes the limit; < stops one earlier. while i <= 5 runs for i = 1..5; while i < 5 runs for i = 1..4.
Off-by-one at the edge is the most common loop bug after the infinite loop. Decide whether the limit itself should run.
Worked example
i = 1
while i < 5:
print(i, end=" ")
i += 1This stops at 4, not 5
Why: When i is 5, 5 < 5 is false, so 5 never prints.
Compare to the earlier <= version
Why: Verified by execution: prints 1 2 3 4. The <= version printed 1 2 3 4 5.
| condition | prints |
|---|---|
| while i <= 5 | 1 2 3 4 5 |
| while i < 5 | 1 2 3 4 |
Blank canvas
Draw it
Draw what <= versus < in the condition just did — the shape of it, not the line-by-line working. One picture, labels only where you need them. Then check it against the steps: anything you could not draw is a step you followed rather than understood.
Section
Part 3
Concept
Start a variable before the loop (often at 0), then add to it each pass. At the end it holds the total.
accumulator — A variable that builds up a result across iterations - a running total, a count, or a joined string.
Ranking
Put in order
Put the moves of Sum 1 through 5 into the order they have to happen.
Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. total grows 0 -> 1 -> 3 -> 6 -> 10 -> 15.
Worked example
total = 0
n = 1
while n <= 5:
total += n
n += 1
print(total)total starts at 0, before the loop
Why: It must exist before we add to it.
Each pass adds the current n, then advances n
Why: total grows 0 -> 1 -> 3 -> 6 -> 10 -> 15.
Trace the running total
Why: Verified by execution: prints 15.
| n | total += n | total |
|---|---|---|
| 1 | 0 + 1 | 1 |
| 2 | 1 + 2 | 3 |
| 3 | 3 + 3 | 6 |
| 4 | 6 + 4 | 10 |
| 5 | 10 + 5 | 15 |
Scale up
Step through it
Step through Sum 1 through 5 and watch the numbers move. Now imagine the input ten times bigger: which column is the one that stops this being practical?
Intuition
Picture total as an empty bucket before the loop. Each pass pours a little more in. After the loop, the bucket holds everything.
Forgetting to create the bucket first (total = 0) is a NameError; resetting it inside the loop empties it every pass.
Sorting
Sort into buckets
These are the pieces of Session 6 - while Loops, out of order. Put each one back under the part of the lesson it belongs to.
Concept
A counter is an accumulator that adds 1 whenever something happens - count += 1 inside an if.
It answers 'how many times did this occur?' across the loop.
Worked example
count = 0
n = 1
while n <= 6:
if n % 2 == 0:
count += 1
n += 1
print(count)count rises only on even n
Why: The if guards the += 1, so it counts 2, 4, 6.
Trace the count
Why: Verified by execution: prints 3.
| n | even? | count |
|---|---|---|
| 1 | no | 0 |
| 2 | yes | 1 |
| 3 | no | 1 |
| 4 | yes | 2 |
| 5 | no | 2 |
| 6 | yes | 3 |
Section
Part 4
Concept
Read input inside the loop and keep going until the user types a special sentinel value - like quit.
sentinel — A chosen value that signals 'stop'. The loop condition compares the input against it: while answer != "quit".
Definition probe
Sort into buckets
Every line below is part of the definition of iteration or of sentinel — one or the other, never both. Put each where it belongs.
Fill the middle
Fill in the blanks
From Repeat until they quit — one line has had its right-hand side removed. Put it back.
message = ""
while message != "quit":
message = input("You: ")
print("Bot heard:", message)
Why: message is what everything below it consumes, so the wrong expression here fails later and somewhere else. message = "" makes the first check true so the loop runs at least once.
Worked example
The user types hi, then quit:
message = ""
while message != "quit":
message = input("You: ")
print("Bot heard:", message)Start message at something that is not the sentinel
Why: message = "" makes the first check true so the loop runs at least once.
Each pass reads and reacts
Why: Verified by execution: it echoes hi, then echoes quit and the next check ends the loop.
| user types | message != "quit" | prints |
|---|---|---|
| hi | True | Bot heard: hi |
| quit | True this pass | Bot heard: quit |
| - | False -> stop | - |
Concept
Give the loop variable a starting value that passes the condition ('prime' it), then read the real input as the first thing inside the loop.
This keeps the sentinel check in one place - on the while line - so the loop stops as soon as the user types it.
Worked example
The user types 5, 8, 2, then 0:
total = 0
x = -1
while x != 0:
x = int(input("Number (0 to stop): "))
total += x
print("Total:", total)0 is the sentinel; adding it changes nothing
Why: Each number is added; the final 0 both stops the loop and adds 0.
Trace the total
Why: Verified by execution: 5 + 8 + 2 + 0 = 15, prints Total: 15.
| x | total |
|---|---|
| 5 | 5 |
| 8 | 13 |
| 2 | 15 |
| 0 | 15 -> stop |
Pattern
Step through it
Step through Sum numbers until 0 one row at a time. What is driving the change, and what would the row after the last one be?
Concept
Sometimes it is clearest to loop while running: and set running = False inside when it is time to stop.
flag — A bool variable that records a yes/no state, like running = True. Flip it to change what the loop does next.
Matching
Match the pairs
Match each term to the definition this lesson gave it — not the one you would guess from the word.
Why: These are the working definitions of iteration, accumulator, sentinel, flag as Session 6 - while Loops uses them. Pairing them correctly is the test of whether you could state each one with the slide switched off.
Fill the middle
Fill in the blanks
From A menu loop with a flag — one line has had its right-hand side removed. Put it back.
running = True
while running:
c = input("1 = play, 3 = quit: ")
if c == "3":
running = False
print("quitting")
else:
print("you chose", c)
Why: running is what everything below it consumes, so the wrong expression here fails later and somewhere else. While running is True the menu repeats; choosing 3 sets running = False.
Worked example
The user types 1, then 3:
running = True
while running:
c = input("1 = play, 3 = quit: ")
if c == "3":
running = False
print("quitting")
else:
print("you chose", c)The flag controls the loop
Why: While running is True the menu repeats; choosing 3 sets running = False.
Trace the passes
Why: Verified by execution: prints you chose 1, then quitting, then stops.
| c | running after | prints |
|---|---|---|
| 1 | True | you chose 1 |
| 3 | False | quitting |
Section
Part 5
Concept
break exits the loop immediately, skipping the rest of the body and any remaining passes.
It is common with while True: - loop forever, and break out when a condition inside is met.
Worked example
k = 0
while True:
if k == 3:
break
print("k", k)
k += 1The condition is always True
Why: So the only way out is the break.
break fires when k reaches 3
Why: Verified by execution: prints k 0, k 1, k 2, then breaks before printing 3.
| k | k == 3? | action |
|---|---|---|
| 0 | no | print k 0 |
| 1 | no | print k 1 |
| 2 | no | print k 2 |
| 3 | yes | break |
Scale up
Step through it
Step through while True with break and watch the numbers move. Now imagine the input ten times bigger: which column is the one that stops this being practical?
Concept
continue abandons the rest of the current pass and jumps straight back to the condition for the next one.
Use it to skip cases you do not care about, without nesting a big if around everything else.
Worked example
m = 0
while m < 6:
m += 1
if m % 2 == 0:
continue
print("odd", m)Advance m first, then test
Why: m += 1 comes before the check so continue cannot skip the update (which would loop forever).
Even numbers are skipped
Why: Verified by execution: prints odd 1, odd 3, odd 5. On even m, continue jumps past the print.
| m | even? | prints |
|---|---|---|
| 1 | no | odd 1 |
| 2 | yes | (skip) |
| 3 | no | odd 3 |
| 4 | yes | (skip) |
| 5 | no | odd 5 |
| 6 | yes | (skip) |
Comparison
Comparison matrix
From Print only the odds: refill the even? column from what you know. The rest of the table is as it appeared.
| m | even? | prints |
|---|---|---|
| 1 | no | odd 1 |
| 2 | yes | (skip) |
| 3 | no | odd 3 |
| 4 | yes | (skip) |
| 5 | no | odd 5 |
| 6 | yes | (skip) |
Anomaly
Predict first
A student writes this, and it looks reasonable:
Looping forever with no way out.
It is wrong. Say what breaks — and say it before you turn the page.
Correct: The condition is always True and there is no break, so it prints hi forever until you force-quit.
Give it an exit: a break on some condition.
Why: The condition is always True and there is no break, so it prints hi forever until you force-quit.
Trap
Looping forever with no way out.
while True:
print("hi")Nothing ever ends it
Why: The condition is always True and there is no break, so it prints hi forever until you force-quit.
| pass | prints |
|---|---|
| 1 | hi |
| ... | hi (forever) |
Give it an exit: a break on some condition.
count = 0
while True:
print("hi")
count += 1
if count == 3:
breakbreak provides the exit
Why: After 3 prints, the break ends the loop. Real output: hi three times, then it stops.
| count | action |
|---|---|
| 1 | hi |
| 2 | hi |
| 3 | hi, then break |
Break the constraint
Discussion prompt
The rule this trap just fixed:
After 3 prints, the break ends the loop. Real output: hi three times, then it stops.
Now break it on purpose. Build a case that violates it and follow the consequences until something visibly fails. Where does the failure first show up — and would you have noticed it if you had not been looking?
Hint: The dangerous rules are the ones whose violation still produces an answer. If yours fails loudly, try to find one that fails quietly.
Answer:
The condition is always True and there is no break, so it prints hi forever until you force-quit.
Intuition
Think of break as a door in the middle of the room. The while condition is the door at the top; break lets you leave from anywhere inside.
continue is different: it is a shortcut back to the top of the room to start the next lap.
Section
Part 6
Concept
Hold a secret number. Loop while the guess is wrong, reading a new guess each pass and giving a higher/lower hint.
The loop naturally ends when the guess equals the secret - the condition becomes false.
Estimation
Predict first
The secret is 7; the user types 3, 9, then 7:
Commit before you compute: what does Guess the number come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.
Correct: Each wrong guess gives a hint; the right one ends the loop
Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. Verified by execution: higher, lower, then You got it!
Worked example
The secret is 7; the user types 3, 9, then 7:
secret = 7
guess = 0
while guess != secret:
guess = int(input("Guess 1-10: "))
if guess < secret:
print("higher")
elif guess > secret:
print("lower")
print("You got it!")Prime guess to something that is not the secret
Why: guess = 0 makes the first check true so the loop runs.
Each wrong guess gives a hint; the right one ends the loop
Why: Verified by execution: higher, lower, then You got it! after 7.
| guess | vs 7 | prints |
|---|---|---|
| 3 | low | higher |
| 9 | high | lower |
| 7 | equal | loop ends |
Pattern
Step through it
Step through Guess the number one row at a time. What is driving the change, and what would the row after the last one be?
Concept
Inside a loop you can use everything from the last sessions: if/elif/else, and/or/not, comparisons, accumulators.
A loop is a stage; the earlier tools are the actors that do the work each pass.
Estimation
Predict first
Same game, now counting attempts. The user types 3, 9, 7:
Commit before you compute: what does Count the guesses too come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.
Correct: Read the output
Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. Verified by execution: three guesses, prints Got it in 3 tries.
Worked example
Same game, now counting attempts. The user types 3, 9, 7:
secret = 7
guess = 0
tries = 0
while guess != secret:
guess = int(input("Guess: "))
tries += 1
print(f"Got it in {tries} tries")An accumulator counts the passes
Why: tries += 1 each loop records how many guesses it took.
Read the output
Why: Verified by execution: three guesses, prints Got it in 3 tries.
| guess | tries |
|---|---|
| 3 | 1 |
| 9 | 2 |
| 7 | 3 -> stop |
Reverse engineer
Discussion prompt
Work backwards. The example finished here:
Read the output
What was it asked to do, and what must it have been given? Reconstruct the problem from its answer.
Hint: Every quantity in the result had to enter somewhere. Account for each one.
Answer:
Same game, now counting attempts. The user types 3, 9, 7:
Section
Part 7
Concept
A loop is perfect for insisting on good input: keep asking until the answer passes your check.
Loop while the value is invalid, reading a new value each pass. It exits only when the input is finally acceptable.
Worked example
The user types -2, 0, then 5:
n = -1
while n <= 0:
n = int(input("A positive number: "))
print("Accepted:", n)Loop while the value is not yet valid
Why: n starts at -1 so the loop runs; it keeps reading while n <= 0.
It exits on the first valid entry
Why: Verified by execution: rejects -2 and 0, accepts 5, prints Accepted: 5.
| n | n <= 0? | action |
|---|---|---|
| -2 | True | ask again |
| 0 | True | ask again |
| 5 | False | accept |
Concept
An accumulator does not have to be a number. Start with an empty string "" and add to it each pass to build up text.
Explain it
Discussion prompt
Explain Building a string in a loop to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.
Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.
Answer:
An accumulator does not have to be a number. Start with an empty string "" and add to it each pass to build up text.
Pattern
Predict first
The table runs: 1 | 1- · 2 | 1-2- · 3 | 1-2-3- · 4 | 1-2-3-4-
In Build 1-2-3-4-5, given the rows so far: what is the next one — the row where i is 5?
Correct: 5 | 1-2-3-4-5
| i | result |
|---|---|
| 1 | 1- |
| 2 | 1-2- |
| 3 | 1-2-3- |
| 4 | 1-2-3-4- |
| 5 | 1-2-3-4-5 |
Why: The relationship between the columns, not the individual numbers, is what generates the next row. result grows one piece per pass; the if avoids a trailing dash.
Worked example
result = ""
i = 1
while i <= 5:
result += str(i)
if i < 5:
result += "-"
i += 1
print(result)Add the number, then a dash (except after the last)
Why: result grows one piece per pass; the if avoids a trailing dash.
Trace the string
Why: Verified by execution: prints 1-2-3-4-5.
| i | result |
|---|---|
| 1 | 1- |
| 2 | 1-2- |
| 3 | 1-2-3- |
| 4 | 1-2-3-4- |
| 5 | 1-2-3-4-5 |
Pattern
Step through it
Step through Build 1-2-3-4-5 one row at a time. What is driving the change, and what would the row after the last one be?
Concept
The while condition is just a condition, so it can combine checks: while attempts < 3 and not unlocked:.
The loop then stops when either the attempts run out or the flag flips - whichever comes first.
Analogy
Discussion prompt
Explain A loop condition can use and / or by analogy to something with no Python Fundamentals in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.
Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.
Answer:
The while condition is just a condition, so it can combine checks: while attempts < 3 and not unlocked:.
Estimation
Predict first
The secret is 1234; the user types 0000, then 1234:
Commit before you compute: what does Limited password attempts come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.
Correct: Trace the attempts
Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. Verified by execution: 0000 fails, 1234 sets unlocked = True, loop ends after 2 attempts.
Worked example
The secret is 1234; the user types 0000, then 1234:
secret = "1234"
attempts = 0
unlocked = False
while attempts < 3 and not unlocked:
pw = input("PIN: ")
attempts += 1
if pw == secret:
unlocked = True
print("Unlocked:", unlocked)Two ways to end: out of tries, or unlocked
Why: The and-condition keeps looping only while there are tries left AND it is still locked.
Trace the attempts
Why: Verified by execution: 0000 fails, 1234 sets unlocked = True, loop ends after 2 attempts. Prints Unlocked: True.
| pw | attempts | unlocked |
|---|---|---|
| 0000 | 1 | False |
| 1234 | 2 | True -> stop |
Blank canvas
Draw it
Draw what Limited password attempts just did — the shape of it, not the line-by-line working. One picture, labels only where you need them. Then check it against the steps: anything you could not draw is a step you followed rather than understood.
Intuition
You can stop from the top - by making the while condition false - or from the middle - with a break.
Both are fine. A clear condition on the while line is often easiest to reason about; break shines when the exit is buried in the middle of the work.
Counterexample
Discussion prompt
You can stop from the top - by making the while condition false - or from the middle - with a break.
That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.
Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.
Answer:
Both are fine. A clear condition on the while line is often easiest to reason about; break shines when the exit is buried in the middle of the work.
Fill the middle
Fill in the blanks
From The same limit with break — one line has had its right-hand side removed. Put it back.
secret = "1234"
attempts = 0
while attempts < 3:
pw = input("PIN: ")
attempts += 1
if pw == secret:
print("Unlocked")
break
Why: pw is what everything below it consumes, so the wrong expression here fails later and somewhere else. The while limits attempts to 3; the break leaves the instant the PIN matches.
Worked example
The user types 0000, then 1234:
secret = "1234"
attempts = 0
while attempts < 3:
pw = input("PIN: ")
attempts += 1
if pw == secret:
print("Unlocked")
breakSame job, exit via break
Why: The while limits attempts to 3; the break leaves the instant the PIN matches.
Read the output
Why: Verified by execution: after the correct 1234, prints Unlocked and breaks. Both styles solve the same problem.
| pw | attempts | action |
|---|---|---|
| 0000 | 1 | loop again |
| 1234 | 2 | Unlocked, break |
Error analysis
Annotate
Walk the callouts on The same limit with break. Each one is a place this is easy to get subtly wrong.
Section
Part 8
Pattern
1. Set up before the loop
Why: Initialize the counter or accumulator (i = 1, total = 0) so the condition and body have something to work with.
2. Write the condition to keep going
Why: while i <= 5: or while answer != "quit":. It should read as 'keep going while ...'.
3. In the body, do the work AND move toward stopping
Why: Print or accumulate, then update the variable the condition depends on (i += 1, read new input).
4. Use break to exit early, continue to skip a pass
Why: break leaves entirely; continue jumps to the next iteration. With while True, you must have a break.
Pattern
Every pass, get closer to false
Why: If the condition depends on i, change i each pass. If it depends on input, read new input each pass.
Never reset the counter inside
Why: i = 1 inside the loop restarts it every pass - a classic freeze. Initialize outside.
With while True, guarantee a break
Why: There must be a reachable condition that runs break, or the loop never ends.
Real world
Discussion prompt
Outside this lesson: where does Session 6 - while Loops actually turn up? Name one concrete situation — a job, a piece of software someone ships, a decision somebody has to make — and say which part of Avoiding infinite loops is doing the work in it.
Hint: Vague is the failure mode here. "Engineering" is not a situation; "deciding whether this build is fast enough to ship" is.
Answer:
Session 6 of the Python Fundamentals series, in depth. Repeating a block with while: the condition checked each pass, the loop variable that must change, counters and countdowns, the infinite-loop trap, accumulators (running totals and counters), sentinel-controlled loops that stop on a chosen value, flags, break and continue, and a full guess-the-number game.
Check
Trace i pass by pass.
i = 1
while i <= 3:
print(i)
i += 1| i | prints? |
|---|---|
| 1 | ? |
| 4 | ? |
Check your understanding
How many numbers does this print?
Answer: A
Why: i runs 1, 2, 3. When i becomes 4, 4 <= 3 is false and the loop ends before printing 4. Verified by execution.
Check
Look for the update.
i = 0
while i < 3:
print("go")| i | changes? |
|---|---|
| 0 | ? |
Check your understanding
What does this do?
Answer: A
Why: i never changes, so i < 3 stays true forever and go prints without end. Adding i += 1 in the body would make it stop. Verified by reasoning (an infinite loop).
Check
Trace total.
total = 0
n = 1
while n <= 4:
total += n
n += 1
print(total)| n | total |
|---|---|
| 1 | ? |
| 4 | ? |
Check your understanding
What does this print?
Answer: A
Why: It adds 1 + 2 + 3 + 4 = 10. total climbs 1, 3, 6, 10. Verified by execution.
Check
When does it leave?
n = 0
while n < 10:
if n == 2:
break
print(n)
n += 1| n | action |
|---|---|
| 0 | ? |
| 2 | ? |
Check your understanding
What does this print?
Answer: A
Why: It prints 0, then 1. When n reaches 2, the break fires before the print, ending the loop. Verified by execution.
Trade off
Comparison matrix
From Check: break: every row here is a choice with a cost. Fill the action column, then say which row you would actually pick and what you give up for it.
| n | action |
|---|---|
| 0 | ? |
| 2 | ? |
Check
What gets skipped?
n = 0
while n < 4:
n += 1
if n == 2:
continue
print(n)| n | prints? |
|---|---|
| 2 | ? |
Check your understanding
What does this print?
Answer: A
Why: continue skips the print only when n == 2, so 2 is omitted and 1, 3, 4 print. n is advanced before the check, so the loop still ends. Verified by execution.
Check
The user types hi, then quit.
msg = ""
while msg != "quit":
msg = input("> ")
print("got", msg)| types | prints |
|---|---|
| hi | ? |
| quit | ? |
Check your understanding
What prints in total?
Answer: A
Why: The sentinel is only checked at the top of the loop. On the pass where quit is typed, the body still runs and prints got quit; the next check then ends the loop. Verified by execution.
Comparison
Comparison matrix
From Check: the sentinel: refill the prints column from what you know. The rest of the table is as it appeared.
| types | prints |
|---|---|
| hi | ? |
| quit | ? |
Connect it up
Draw it
One page, no notation unless you need it: draw how these connect — Repeating with while · The Infinite Loop · Building Up a Result · Loops that Listen · break and continue · Build a Game. Put an arrow wherever one of them is what makes another possible, and label the arrow with why.
Recap
A while loop repeats its block while a condition holds. Set up before, do work and move toward stopping inside, and end when the condition turns false.
| You want | Use |
|---|---|
| repeat a fixed count | counter + while i <= n |
| build a total | accumulator (total += ...) |
| stop on a value | sentinel (while x != "quit") |
| leave early | break |
| skip one pass | continue |
Always make sure each pass gets closer to stopping, or the loop runs forever. Next session we meet the for loop and lists - looping over a collection of items.
Want this taught 1-on-1? Alexander tutors Python Fundamentals — $55/session, free consultation.