1.2.17 · D3Introduction to Programming (Python)

Worked examples — while loop — condition-based, infinite loop dangers

2,528 words11 min readBack to topic

The scenario matrix

Here is every class of situation a while loop can hand you. Think of it as a checklist — if you can solve one example from each row, you have seen the whole beast.

# Case class What makes it distinct Covered by
A Counts down to zero update decreases toward boundary Ex 1
B Counts up to a limit update increases toward boundary Ex 2
C Zero-iteration (body never runs) condition already False on entry Ex 3
D Exactly-one iteration (boundary edge) condition true once, then false Ex 3
E Float never lands exactly == on floats loops forever Ex 4
F Unknown count, data-driven user input decides the length Ex 5
G while True + break (deliberate infinite) condition is a constant Ex 6
H Accidental infinite (missing/misplaced update) update outside the live path Ex 7
I Real-world word problem (converging quantity) model reality as a boundary Ex 8
J Exam twist: nested / off-by-one counting count the checks, not the prints Ex 9

We now hit all ten cells.


Worked examples

Case A — counting down to a boundary


Case B — counting up to a limit

Figure — while loop — condition-based, infinite loop dangers

Cases C & D — zero and exactly-one iterations


Case E — the float that never lands


Case F — unknown count, data driven


Case G — deliberate infinite loop with break


Case H — the accidental infinite loop


Case I — real-world word problem


Case J — exam twist: nested loops & counting checks

Figure — while loop — condition-based, infinite loop dangers

Recall Active recall — cover the answers
  • In Example 1, how many times is n > 0 checked? ::: 4 times (3 True + 1 final False).
  • Why does Example 3 Case C print nothing? ::: pre-test loop; condition 5 < 5 is False on entry so the body runs zero times.
  • Why does the float loop in Example 4 never end? ::: 0.1 isn't stored exactly, so the sum skips over 1.0; == never matches. Use <.
  • What froze Example 7 at i = 1? ::: continue skipped the i += 1 update, so the condition never advanced.
  • Bacteria: first hour exceeding 1000 starting at 50, doubling? ::: 5 hours (reaching 1600).
  • Nested loop count in Example 9? ::: 6 (outer 2 × inner 3).

Connections

Concept Map

scenario matrix

direction of update

boundary edge cases

infinite loops

count down Ex1

count up Ex2

zero runs Ex3

one run Ex3

off by one Ex1 Ex9

deliberate while True Ex6

float equals Ex4

continue skips update Ex7

word problem Ex8

nested loops Ex9