Session 6 - while Loops

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

What this lesson covers

The lesson, slide by slide

1. while Loops

Title

Python Fundamentals - Session 6

Keep going until the program decides to stop

2. What you will be able to do

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:

  1. Write a while loop that repeats a block while a condition stays true.
  2. Trace a counter and a running total pass by pass.
  3. Explain what causes an infinite loop and how to avoid it.
  1. Stop a loop on a sentinel value or with break.
  2. Skip an iteration with continue.
  3. Build a guess-the-number game.

3. What survived from Session 5 - Comparisons & Logic (and / or / not)?

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.

4. Repeating with while

Section

Part 1

5. A loop repeats a block

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.

6. Break it if you can: A loop repeats a block

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.

7. Repeat-until, out loud

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.

8. By analogy: Repeat-until, out loud

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'.

9. The three moving parts

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.

10. Teach it back: The three moving parts

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.

11. What has to happen first: Count 1 to 5

Ranking

Put in order

Put the moves of Count 1 to 5 into the order they have to happen.

  1. Before the loop: i starts at 1
  2. Each pass: print i, then add 1
  3. Trace every pass

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.

12. Count 1 to 5

Worked example

i = 1
while i <= 5:
    print(i, end=" ")
    i += 1

Before 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 <= 5iprints
True11
True22
True33
True44
True55
False6stop

13. Fill in: i for Count 1 to 5

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 <= 5iprints
True11
True22
True33
True44
True55
False6stop

14. The loop variable must change

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.

15. Predict the next row: A countdown

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 > 0cprints
True3T-minus 3
True2T-minus 2
True1T-minus 1
False0Liftoff!

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.

16. A countdown

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 > 0cprints
True3T-minus 3
True2T-minus 2
True1T-minus 1
False0Liftoff!

17. What each one costs: A countdown

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 > 0cprints
True3T-minus 3
True2T-minus 2
True1T-minus 1
False0Liftoff!

18. A multiplication table

Worked example

i = 1
while i <= 5:
    print(f"3 x {i} = {3 * i}")
    i += 1

The 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.

iprints
13 x 1 = 3
23 x 2 = 6
33 x 3 = 9
43 x 4 = 12
53 x 5 = 15

19. Watch it run: A multiplication table

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?

  1. Step 1: i is 1
  2. Step 2: i is 2
  3. Step 3: i is 3
  4. Step 4: i is 4
  5. Step 5: i is 5

20. The Infinite Loop

Section

Part 2

21. If nothing changes, it never stops

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.

22. Something is wrong here: forgetting to update

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.

23. Trap: forgetting to update

Trap

The 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.

passicondition
11True
21True
...1True (forever)

The fix

Update the variable the condition depends on.

i = 1
while i <= 5:
    print(i)
    i += 1

i += 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.

passicondition
11True
55True
66False -> stop

24. Inspect it line by line: Trap: forgetting to update

Error analysis

Annotate

Walk the callouts on Trap: forgetting to update. Each one is a place this is easy to get subtly wrong.

  • There is no i += 1, so i <= 5 is always true. It prints 1 endlessly and never stops on its own.
  • Now i climbs 1..5 and the loop ends when i is 6. Real output: 1 through 5, then it stops.

25. The exit must get closer

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.

26. Watch the comparison at the edge

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.

27. <= versus < in the condition

Worked example

i = 1
while i < 5:
    print(i, end=" ")
    i += 1

This 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.

conditionprints
while i <= 51 2 3 4 5
while i < 51 2 3 4

28. Draw the shape of it: <= versus < in the condition

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.

29. Building Up a Result

Section

Part 3

30. An accumulator variable

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.

31. What has to happen first: Sum 1 through 5

Ranking

Put in order

Put the moves of Sum 1 through 5 into the order they have to happen.

  1. total starts at 0, before the loop
  2. Each pass adds the current n, then advances n
  3. Trace the running total

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.

32. Sum 1 through 5

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.

ntotal += ntotal
10 + 11
21 + 23
33 + 36
46 + 410
510 + 515

33. What happens as it grows: Sum 1 through 5

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?

  1. Step 1: n is 1
  2. Step 2: n is 2
  3. Step 3: n is 3
  4. Step 4: n is 4
  5. Step 5: n is 5

34. The total is a bucket you fill

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.

35. Where does each piece belong: Session 6 - while Loops

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.

Repeating with while
A loop repeats a block; Repeat-until, out loud; The three moving parts
The Infinite Loop
If nothing changes, it never stops; The exit must get closer; Watch the comparison at the edge
Building Up a Result
An accumulator variable; Sum 1 through 5; The total is a bucket you fill
s1
Repeating with while is where Session 6 - while Loops puts A loop repeats a block, Repeat-until, out loud, The three moving parts. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.
s2
The Infinite Loop is where Session 6 - while Loops puts If nothing changes, it never stops, The exit must get closer, Watch the comparison at the edge. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.
s3
Building Up a Result is where Session 6 - while Loops puts An accumulator variable, Sum 1 through 5, The total is a bucket you fill. Knowing which part of the lesson a problem belongs to is most of knowing which method to reach for.

36. Counting is accumulating by 1

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.

37. Count the even numbers

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.

neven?count
1no0
2yes1
3no1
4yes2
5no2
6yes3

38. Loops that Listen

Section

Part 4

39. A sentinel value ends the loop

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".

40. Take the definitions apart: iteration vs sentinel

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.

iteration
One pass through the loop body.; A loop that runs its block five times has five iterations.
sentinel
A chosen value that signals 'stop'.; The loop condition compares the input against it
b1
One pass through the loop body. A loop that runs its block five times has five iterations.
b2
A chosen value that signals 'stop'. The loop condition compares the input against it: while answer != "quit".

41. Restore the missing line: Repeat until they quit

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.

42. Repeat until they quit

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 typesmessage != "quit"prints
hiTrueBot heard: hi
quitTrue this passBot heard: quit
-False -> stop-

43. Prime the loop, then read inside

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.

44. Sum numbers until 0

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.

xtotal
55
813
215
015 -> stop

45. Watch it run: Sum numbers until 0

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?

  1. Step 1: x is 5
  2. Step 2: x is 8
  3. Step 3: x is 2
  4. Step 4: x is 0

46. A flag variable

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.

47. Term to definition: Session 6 - while Loops

Matching

Match the pairs

Match each term to the definition this lesson gave it — not the one you would guess from the word.

  • t1. iteration
  • t2. accumulator
  • t3. sentinel
  • t4. flag
  • d1. One pass through the loop body. A loop that runs its block five times has five iterations.
  • d2. A variable that builds up a result across iterations - a running total, a count, or a joined string.
  • d3. A chosen value that signals 'stop'. The loop condition compares the input against it: while answer != "quit".
  • d4. A bool variable that records a yes/no state, like running = True. Flip it to change what the loop does next.

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.

48. Restore the missing line: A menu loop with a flag

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.

49. A menu loop with a flag

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.

crunning afterprints
1Trueyou chose 1
3Falsequitting

50. break and continue

Section

Part 5

51. break: leave the loop now

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.

52. while True with break

Worked example

k = 0
while True:
    if k == 3:
        break
    print("k", k)
    k += 1

The 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.

kk == 3?action
0noprint k 0
1noprint k 1
2noprint k 2
3yesbreak

53. What happens as it grows: while True with 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?

  1. Step 1: k is 0
  2. Step 2: k is 1
  3. Step 3: k is 2
  4. Step 4: k is 3

54. continue: skip to the next pass

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.

55. Print only the odds

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.

meven?prints
1noodd 1
2yes(skip)
3noodd 3
4yes(skip)
5noodd 5
6yes(skip)

56. Fill in: even? for Print only the odds

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.

meven?prints
1noodd 1
2yes(skip)
3noodd 3
4yes(skip)
5noodd 5
6yes(skip)

57. Something is wrong here: while True with no break

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.

58. Trap: while True with no break

Trap

The 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.

passprints
1hi
...hi (forever)

The fix

Give it an exit: a break on some condition.

count = 0
while True:
    print("hi")
    count += 1
    if count == 3:
        break

break provides the exit

Why: After 3 prints, the break ends the loop. Real output: hi three times, then it stops.

countaction
1hi
2hi
3hi, then break

59. Break it on purpose: while True with no 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.

60. break is the emergency exit

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.

61. Build a Game

Section

Part 6

62. The guess-the-number shape

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.

63. Guess the shape of the answer: Guess the number

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!

64. Guess the number

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.

guessvs 7prints
3lowhigher
9highlower
7equalloop ends

65. Watch it run: Guess the number

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?

  1. Step 1: guess is 3
  2. Step 2: guess is 9
  3. Step 3: guess is 7

66. Combine a loop with logic

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.

67. Guess the shape of the answer: Count the guesses too

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.

68. Count the guesses too

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.

guesstries
31
92
73 -> stop

69. Work backwards from the answer: Count the guesses too

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:

70. More Loop Patterns

Section

Part 7

71. Input validation: keep asking

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.

72. Ask until positive

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.

nn <= 0?action
-2Trueask again
0Trueask again
5Falseaccept

73. Building a string in a loop

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.

74. Teach it back: Building a string in a loop

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.

75. Predict the next row: Build 1-2-3-4-5

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

iresult
11-
21-2-
31-2-3-
41-2-3-4-
51-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.

76. Build 1-2-3-4-5

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.

iresult
11-
21-2-
31-2-3-
41-2-3-4-
51-2-3-4-5

77. Watch it run: Build 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?

  1. Step 1: i is 1
  2. Step 2: i is 2
  3. Step 3: i is 3
  4. Step 4: i is 4
  5. Step 5: i is 5

78. A loop condition can use and / or

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.

79. By analogy: A loop condition can use and / or

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:.

80. Guess the shape of the answer: Limited password attempts

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.

81. Limited password 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.

pwattemptsunlocked
00001False
12342True -> stop

82. Draw the shape of it: Limited password attempts

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.

83. Two ways to stop a loop

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.

84. Break it if you can: Two ways to stop a loop

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.

85. Restore the missing line: The same limit with break

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.

86. The same limit with break

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")
        break

Same 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.

pwattemptsaction
00001loop again
12342Unlocked, break

87. Inspect it line by line: The same limit with 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.

  • The while limits attempts to 3; the break leaves the instant the PIN matches.
  • Verified by execution: after the correct 1234, prints Unlocked and breaks. Both styles solve the same problem.

88. Patterns & Checks

Section

Part 8

89. Writing a while loop

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.

90. Avoiding infinite loops

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.

91. Where this shows up: Session 6 - while Loops

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.

92. Check: count the passes

Check

Trace i pass by pass.

i = 1
while i <= 3:
    print(i)
    i += 1
iprints?
1?
4?

Check your understanding

How many numbers does this print?

  • A. Three (1, 2, 3) (correct)
  • B. Four (1, 2, 3, 4)
  • C. Two (1, 2)
  • D. It never stops

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.

Why B tempts people
4 is never printed - the condition i <= 3 is false at i = 4, so the loop stops first.
Why C tempts people
i = 3 still satisfies 3 <= 3, so 3 does print. That is three numbers, not two.
Why D tempts people
i += 1 moves i toward 4, so the condition eventually fails - it does stop.

93. Check: the missing update

Check

Look for the update.

i = 0
while i < 3:
    print("go")
ichanges?
0?

Check your understanding

What does this do?

  • A. Prints go forever (infinite loop) (correct)
  • B. Prints go three times
  • C. Prints go once
  • D. Prints nothing

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).

Why B tempts people
There is no i += 1, so i stays 0 and the loop never advances toward 3.
Why C tempts people
The condition is true every pass, so it prints repeatedly, not once.
Why D tempts people
0 < 3 is true, so the body runs - and keeps running.

94. Check: the running total

Check

Trace total.

total = 0
n = 1
while n <= 4:
    total += n
    n += 1
print(total)
ntotal
1?
4?

Check your understanding

What does this print?

  • A. 10 (correct)
  • B. 6
  • C. 4
  • D. 15

Answer: A

Why: It adds 1 + 2 + 3 + 4 = 10. total climbs 1, 3, 6, 10. Verified by execution.

Why B tempts people
6 is the total after n = 3 (1 + 2 + 3). The loop also runs for n = 4, adding 4.
Why C tempts people
4 is only the last number added, not the sum of all of them.
Why D tempts people
15 would be 1 + 2 + 3 + 4 + 5, but the loop stops after 4 (n <= 4).

95. Check: break

Check

When does it leave?

n = 0
while n < 10:
    if n == 2:
        break
    print(n)
    n += 1
naction
0?
2?

Check your understanding

What does this print?

  • A. 0 then 1 (correct)
  • B. 0, 1, 2
  • C. 0 through 9
  • D. nothing

Answer: A

Why: It prints 0, then 1. When n reaches 2, the break fires before the print, ending the loop. Verified by execution.

Why B tempts people
2 is never printed - the break runs first, before the print on that pass.
Why C tempts people
The break exits early at n = 2, so it never reaches 9.
Why D tempts people
n = 0 and n = 1 both print before the break, so it is not empty.

96. What each one costs: Check: break

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.

naction
0?
2?

97. Check: continue

Check

What gets skipped?

n = 0
while n < 4:
    n += 1
    if n == 2:
        continue
    print(n)
nprints?
2?

Check your understanding

What does this print?

  • A. 1, 3, 4 (correct)
  • B. 1, 2, 3, 4
  • C. 2
  • D. 1, 3

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.

Why B tempts people
2 is skipped by the continue, so it does not print.
Why C tempts people
continue skips 2; it does not print only 2. The others print normally.
Why D tempts people
4 also prints - the loop runs while n < 4, and n reaches 4 on the last pass.

98. Check: the sentinel

Check

The user types hi, then quit.

msg = ""
while msg != "quit":
    msg = input("> ")
    print("got", msg)
typesprints
hi?
quit?

Check your understanding

What prints in total?

  • A. got hi, then got quit (correct)
  • B. only got hi
  • C. got hi, got quit, then loops again
  • D. nothing

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.

Why B tempts people
quit is read and printed within the same pass before the condition is re-checked.
Why C tempts people
After printing got quit, the top-of-loop check msg != "quit" is false, so it does not loop again.
Why D tempts people
The loop runs at least once (msg starts as ""), so it prints.

99. Fill in: prints for Check: the sentinel

Comparison

Comparison matrix

From Check: the sentinel: refill the prints column from what you know. The rest of the table is as it appeared.

typesprints
hi?
quit?

100. Connect it up: Session 6 - while Loops

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.

101. What you can do now

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 wantUse
repeat a fixed countcounter + while i <= n
build a totalaccumulator (total += ...)
stop on a valuesentinel (while x != "quit")
leave earlybreak
skip one passcontinue

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.

Sources

  1. Python 3 Tutorial - The while statement and Control Flow
  2. Python 3 Tutorial - break, continue
  3. All snippets executed and copied from CPython 3.12; input shown as typed values. — Author verification run, 2026-07-15 (Python Fundamentals series, Session 6).

Want this taught 1-on-1? Alexander tutors Python Fundamentals — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108