Week 5 — While Loops

Interactive demos for Week 5 labs. Each lab supports a method toggle so you can step through the same trace with two natural ways of writing the loop. Pick a lab below.

Lab 5.18 — Countdown Until Matching Digits

This demo traces the program with input 93. The expected output is 93 92 91 90 89 88. There are two natural ways to ask “do the two digits match?” — comparing the first and last characters of str(n), or comparing n // 10 with n % 10. Use the toggle below to run the same trace with either method — the loop behavior is identical, only how we phrase the question changes.

Input: 93  ·  Expected output: 93 92 91 90 89 88
Method
str(n)[0] != str(n)[1]
1 / 7
Variables

Lab 5.19 — Mad Lib (sentinel loop)

Repeatedly read a word and a number; print the Mad Lib sentence; stop when the word is quit (the integer that comes with quit is read but never used). Two natural ways to “grab the word”: index into line.split()[0], or unpack the split with word, num = input().split(). The interesting pattern here is the priming read: read once before the loop, again at the end of the body — that’s how a while-driven sentinel loop checks before it consumes.

Stdin: apples 5 · shoes 2 · quit 0  ·  Expected output: two “Eating … a day keeps you happy and healthy.” sentences
Method
while line.split()[0] != 'quit':
1 / 5
Variables