Week 5 — Lecture Outline · Loops I: the `while` loop
Course: Introduction to Computer Science — CS1 / Programming Fundamentals in Python (CSCI 1101) · Silver Oak University (fictional sample) · Prof. Okafor
Objective covered: Objective 4 — Write while loops with counters and accumulators; trace a loop's final value and iteration count; diagnose and fix infinite loops and off-by-one errors.
SLOs touched: A (write and run a correct loop) · B (trace a loop, predict its output and iteration count; find and fix a loop defect)
Meeting pattern: 2 studio sessions × 75 min = 150 min. Segment minutes below total ~150; scale to your own pattern.
Every loop output, counter value, accumulator total, and iteration count in this outline was produced by actually running the code in Python — not hand-traced. Run them live in class; the outputs are exact. Safety note for the whole week: to demonstrate an infinite loop, show the buggy code but only ever run a bounded version (or add a small cap). Never run a truly unbounded loop in front of the class without a way to stop it — if one starts, press Ctrl+C (terminal) or click Stop (online editor).
Week at a Glance
| The week's big question | "How do you make a program repeat — and how do you make sure it eventually stops?" |
| By the end of the week, students can… | (1) write a while loop with a counter and an accumulator; (2) trace a loop and predict its final value and how many times it runs, then confirm by running it; (3) explain the off-by-one difference between < and <=; (4) diagnose an infinite loop (missing counter update), stop it (Ctrl+C), and fix it; (5) use break to leave a loop early. |
| Key vocabulary | loop, while, condition, body, iteration, counter, increment (count = count + 1, count += 1), accumulator, running total, loop variable, termination, off-by-one, < vs <=, infinite loop, Ctrl+C (interrupt), break, while True |
| Materials | slides (Deck 5), the week's readings + video links, a free online Python environment + Python Tutor (links in the readings), one approved chatbot (Gemini / Claude / ChatGPT) for the AI-critique moment and the tutorial |
| Timing note | 8 segments, ~150 min total. Session 1 = Segments 1–4 (~75). Session 2 = Segments 5–8 (~75). This is a studio: code along on the projector and have students type and run every loop with you — and count the iterations out loud together. |
Segment 1 — Hook & the Promise (8 min) · Session 1 opens
Hook. Stand at the front and say: "I want to count out loud from 1 to 5. Watch what I do." Then count "1, 2, 3, 4, 5 — done." Ask: "What did I actually do five times?" Draw it out of them: you said a number, then went up by one, and checked whether you'd passed 5. That's a loop. Then ask the dangerous version: "What if I never agreed to stop at 5?" — and count "6, 7, 8…" until they laugh and tell you to stop. That's an infinite loop, and 'tell you to stop' is Ctrl+C.
The promise (write it on the board): "By Friday you'll make a program repeat as many times as you want, build a running total while it runs, and — the part that makes looping click — predict exactly how many times it runs before you press Run."
Why it matters line (memory hook): "Every loop needs three things: a START, a STOP, and a STEP. Forget the step, and it never stops."
Segment 2 — What Is a Loop? The while Condition + Body (18 min)
Plain language first. A loop repeats a block of code. A while loop repeats its body as long as a condition is true. The condition is exactly the kind of True/False expression from Week 4. Each time through is one iteration.
The anatomy (put it on a slide):
while CONDITION: # checked BEFORE each pass; while it's True, run the body
BODY # indented — the lines that repeat
"Read it as: 'while this is true, keep doing this.' Python checks the condition first. If it's True, it runs the indented body, then goes back up and checks the condition again. The moment the condition is False, it skips the body and moves on."
The three parts every counting loop needs (the memory hook):
1. START — set the counter before the loop (count = 1).
2. STOP — the condition that ends it (while count <= 5:).
3. STEP — update the counter inside the body (count = count + 1) so the loop moves toward stopping.
The clarification students always need: the condition is not re-checked in the middle of the body — only at the top, before each pass. And if the step is missing, the condition never becomes False and the loop runs forever. We'll see that on purpose later.
Segment 3 — Counters & Accumulators: the code-along (26 min)
Set it up: "Open the online Python environment. Type exactly what I type, run it, and we'll count the iterations together."
Code-along #1 — a counter (everyone types and runs):
count = 1
while count <= 5:
print(count)
count = count + 1
print("done, count is", count)
Run it. Output (run-verified):
1
2
3
4
5
done, count is 6
"Walk the three parts: START count = 1; STOP while count <= 5; STEP count = count + 1. It printed 1 through 5 — five iterations. Notice the surprise at the end: after the loop, count is 6, not 5. The loop ran with count at 5, printed it, stepped to 6, checked 6 <= 5 → False, and stopped. The counter always ends one past the last value that passed the condition."
Name the shorthand: count = count + 1 is so common Python gives it a shortcut: count += 1. They mean the same thing. (Same for total += i.)
Code-along #2 — an accumulator (a running total):
total = 0
i = 1
while i <= 5:
total = total + i
i = i + 1
print(total)
Run it. Output (run-verified):
15
"An accumulator is a variable that builds up a result across iterations. Start it at 0 (the identity for addition), then add something each pass. Here we add i (1, then 2, … then 5): 0+1+2+3+4+5 = 15. The pattern — initialize, then update inside the loop — is the single most useful loop pattern in the course."
Show the running total live (paste and run):
total = 0
i = 1
while i <= 4:
total = total + i
print(i, total)
i = i + 1
Output (run-verified):
1 1
2 3
3 6
4 10
"Watch the second column build: 1, 3, 6, 10. That column IS the accumulator. The first column is the counter driving the loop."
Segment 4 — Trace This Code: Predict the Final Value & the Iteration Count (20 min) · Session 1 closes (~75)
Set it up: "A real programmer predicts a loop before running it — what's the final value, and how many times does it run? Let's trace, then run to check."
Worked trace (reveal one line at a time; have the room predict BOTH the final value and the count):
i = 0
while i < 7:
print(i)
i = i + 1
- Trace the START/STOP/STEP:
ibegins at 0; condition isi < 7; step is+1. - Predict the values printed: 0, 1, 2, 3, 4, 5, 6. When
ireaches 7,7 < 7is False → stop. So it runs 7 times (once for each of 0–6), andiends at 7. - Run it. Output (run-verified):
0
1
2
3
4
5
6
"Count them: seven lines. A loop while i < n starting from 0 runs n times. This is the single most useful counting fact of the week."
Worked trace #2 — an accumulator's final total:
total = 0
n = 1
while n <= 6:
total = total + n
n = n + 1
print(total)
- Trace: add 1+2+3+4+5+6. Predict
21. - Output (run-verified):
21
Quick interaction (rapid-fire, ~5 min): put three loops on a slide; for each, students predict how many times it runs (20 sec), then you run it.
- i = 2 / while i < 10: / print(i) / i = i + 2 → prints 2 4 6 8 (run-verified) — 4 times.
- n = 3 / while n > 0: / print(n) / n = n - 1 → prints 3 2 1 (run-verified) — 3 times (a countdown).
- c = 0 / while c < 3: / c += 1 / then print(c) → prints 3 (run-verified) — runs 3 times, ends at 3.
Segment 5 — Off-by-One: < vs <= (18 min) · Session 2 opens
Hook back in: "Last session you counted loops. Today we meet the single most common loop mistake — being off by one — and it almost always comes down to one character: < versus <=."
Plain language first. The condition decides the last value that gets in. < stops one short; <= includes the boundary.
Side-by-side demo (run both):
i = 1
while i < 5:
print(i)
i = i + 1
Output (run-verified):
1
2
3
4
versus
i = 1
while i <= 5:
print(i)
i = i + 1
Output (run-verified):
1
2
3
4
5
"Same loop, one character different. i < 5 prints 1–4 (stops one short of 5). i <= 5 prints 1–5 (includes 5). If you wanted 'the numbers 1 through 5' and you used < 5, you'd be off by one — you'd silently miss the 5. The program runs fine; it just gives the wrong answer."
Land the distinction (put it on a slide):
- while count < n: runs while count is below n → the boundary n is excluded.
- while count <= n: runs while count is at or below n → the boundary n is included (one more iteration).
Memory hook: "< n stops one short of n; <= n includes n."
Misconception + cure:
- ❌ "< 5 and <= 5 are basically the same — close enough."
✅ Cure: they differ by exactly one iteration, and that one iteration is the difference between right and wrong. When you want a specific count, decide on purpose: do I want to include the boundary or not? Then run it and count.
Segment 6 — Spot & Fix the Bug: the Infinite Loop (20 min)
Set it up (say the safety rule out loud): "I'm going to show you the most famous loop bug — the infinite loop. We will read the broken code, but we will not run it as written, because it never stops. To see what it does, we'll run a safe, capped version. If a loop ever runs away from you for real, press Ctrl+C in a terminal or Stop in the editor."
The buggy program (put it on a slide exactly as is — DO NOT RUN as written):
count = 1
while count < 5:
print(count)
# BUG: we never update count, so count stays 1 forever
Debug it out loud:
1. Find the three parts. START: count = 1 ✓. STOP: while count < 5 ✓. STEP: missing! There's no count = count + 1.
2. Because count never changes, count < 5 is always True, so the loop runs forever, printing 1 endlessly.
3. How to stop it if it's running: Ctrl+C (terminal) or the Stop button (online editor). That interrupts the program.
4. The fix — add the STEP, then run to confirm:
count = 1
while count < 5:
print(count)
count = count + 1
Output (run-verified):
1
2
3
4
"One line — the missing count = count + 1 — turns an infinite loop into a loop that prints 1–4 and stops. A loop must make progress toward its stopping condition. Forgetting the step is the #1 way to write an infinite loop."
To SAFELY demonstrate 'it's stuck' (run THIS bounded version, not the real bug):
count = 1
guard = 0
while count < 5: # would be infinite: count never changes
guard = guard + 1
if guard >= 3: # safety cap so this is SAFE to run
print("still stuck: count is", count, "after", guard, "passes")
break
Output (run-verified):
still stuck: count is 1 after 3 passes
"The guard and break are only here so we can run it safely — they let us watch count sit at 1 while the loop spins. In the real bug there's no guard; that's why it never stops."
A second quick bug (let the room solve it) — an off-by-one: a program meant to sum the numbers 1 through 5 but written with < 5:
n = 5
total = 0
i = 1
while i < n: # BUG: should be <= n to include 5
total = total + i
i = i + 1
print(total)
Run it → 10 (run-verified) — but the intended answer (1+2+3+4+5) is 15. The bug: < n stops at 4, missing the 5. Fix: while i <= n: → 15 (run-verified).
Segment 7 — break, Misconceptions Round-Up + Quick Interaction (20 min)
break — leave a loop early (teach + run): sometimes you want to stop the moment something happens, not when the condition runs out. break exits the loop immediately.
total = 0
i = 1
while i <= 100:
total = total + i
if total > 10:
print("stopped at i =", i, "total =", total)
break
i = i + 1
Output (run-verified):
stopped at i = 5 total = 15
"We were ready to go to 100, but the moment the running total passed 10, break jumped us out. break is your manual stop — and it's also how you safely use while True: (a deliberate 'loop forever') as long as something inside breaks out."
A while True with a break (run-verified) — find the first number whose square is over 50:
n = 1
while True:
if n * n > 50:
print(n)
break
n = n + 1
Output: 8 (because 8 × 8 = 64 > 50; 7 × 7 = 49 is not). "while True looks like an infinite loop — and it would be, without the break. The break is the STOP."
Name the misconceptions out loud, then cure each:
- ❌ "The loop checks the condition in the middle and stops as soon as it goes false."
✅ Cure: it only checks at the top, before each pass. The body always finishes once it starts.
- ❌ "< n and <= n give the same loop."
✅ Cure: they differ by exactly one iteration. < n excludes n; <= n includes it.
- ❌ "If a loop is slow/stuck, the computer is broken."
✅ Cure: it's almost always an infinite loop — a missing step. Ctrl+C to stop, then add the counter update.
- ❌ "After while count < 5, count ends at 5."
✅ Cure: it ends at 6 — one past the boundary. The loop steps, then re-checks. Run it.
- ❌ "while True is always a bug."
✅ Cure: it's a common, fine pattern as long as a break inside ends it.
Interaction — Predict-then-Run (rapid-fire, ~6 min): put four loops on a slide; students predict the output AND the iteration count solo (30 sec), compare with a neighbor (1 min), then you run all four (all run-verified):
- i = 0 / while i <= 10: / print(i) / i = i + 2 → 0 2 4 6 8 10 — 6 times.
- n = 3 / while n >= 0: / print(n) / n = n - 1 → 3 2 1 0 — 4 times (note >= 0 includes 0).
- product = 1 / i = 1 / while i <= 4: / product = product * i / i = i + 1 / print(product) → 24 (an accumulator that multiplies).
- i = 10 / while i > 0: / print(i) / i = i - 3 → 10 7 4 1 — 4 times.
Tally how many the room got right — celebrate the off-by-one misses as "this is exactly why we run loops and count."
Segment 8 — Technology Workflow + AI-Critique, Callback & Hand-off (18 min) · Session 2 closes (~75)
Technology workflow — tracing a loop step by step:
1. Open the free online Python environment (link in the readings). Type your loop.
2. Before running, predict the final value and the iteration count.
3. Press Run, read the output, count the lines. If it's stuck, Ctrl+C / Stop.
4. To watch the counter change one pass at a time, paste the loop into Python Tutor and click forward — you'll see count tick up and the condition flip to False.
AI-critique moment (students verify, not consume):
Paste this to an approved chatbot: "How many times does this loop run, and what does it print?
i = 1thenwhile i <= 5:print(i)i = i + 1. Also: what is the final value ofiafter the loop?"
Then check by running it. Chatbots are genuinely weak on loops: they miscount iterations and routinely get the off-by-one wrong (saying a<= 5loop runs 5 times but also claimingiends at 5 — it ends at 6), and they'll state it with total confidence. Your job all semester: the tool drafts, you run it and count. This is exactly how the weekly Lecture Tutorial and Coding Lab work — you catch the model, not trust it.
Callback + tease:
- Callback: "Today: how to make a program repeat with while, build counters and accumulators, predict a loop's final value and iteration count, fix an infinite loop, and use break. Every line of this builds on Week 4's True/False conditions — the loop's condition IS a Boolean."
- Tease next week: "The while loop is great when you don't know in advance how many times to repeat. But when you DO know — 'do this for each of the numbers 0 to 9' — there's a cleaner tool. Next week: Loops II — the for loop, range(), and nested loops. You'll write the same counting loops in half the lines."
Hand-off (the week's graded work):
- Lecture Tutorial 5 (AI tutor, share-link submission) — while loops, counters, accumulators, off-by-one, infinite loops, break.
- Quiz 5, Discussion 5 ("How Do You Actually Find the Bug?" — the debugging-strategy debate), and Assignment 5 ("Loops That Count").
- Coding Lab 5 — "Count, Total, Stop" — write a counter + accumulator, complete a predict-then-run table, fix an infinite-loop / off-by-one bug, and visualize a loop in Python Tutor.
Instructor FAQ — Common Stumbles
| Student says / does | Quick cure |
|---|---|
| Writes a loop with no counter update; it hangs. | Classic infinite loop — the STEP is missing. Ctrl+C / Stop, then add count = count + 1 inside the body. |
| "My loop is one short / one too many." | Off-by-one. Check < vs <=: < n excludes n, <= n includes it. Decide which boundary you want, then run and count. |
Expects count to end at 5 after while count <= 5. |
It ends at 6 — the loop steps, then re-checks the condition. Have them print count after the loop. |
| Forgets to initialize the accumulator. | Set total = 0 (or product = 1) before the loop, or it's undefined (NameError) or carries an old value. |
| Indents the counter update outside the loop body. | If count = count + 1 isn't indented under while, it runs only after the loop — making the loop infinite. Indentation decides what repeats. |
Uses while True and panics. |
That's fine if a break inside ends it. Show them the break is the STOP. No break → infinite. |
| Thinks the condition is checked mid-body. | It's checked only at the top, before each pass; the body always finishes once started. Python Tutor makes this obvious. |
| Asks an AI "how many times does this run?" and trusts it. | Chatbots miscount loops. Run it and count the lines. That's the AI-critique habit. |
Scope flag
This outline stays within Objective 4, the while half (loop conditions; counters; accumulators; termination; the <-vs-<= off-by-one; infinite loops and how to stop them; break). for loops, range(), and nested loops are Week 6 and only teased here. We use only this-week constructs plus prior weeks' print, variables/arithmetic (W2), and Boolean conditions and if (W4) — the right floor for a first loops week. No example loop in this file runs unbounded: the infinite-loop bug is shown as code and only run in a capped, break-guarded form. Python is referenced factually; the instructor and institution remain fictional. Every output shown was produced by running the code.
~ Prof. Okafor's edition · Fall 2026 · built with thecoursemaker.com