Loops — while & for
6. Loops — while & for
6.1Repeating While True (while Loops)
Think of an alarm clock — it keeps ringing WHILE you haven't hit the snooze button.
SHOW:
WHAT HAPPENED HERE
count > 0. Each loop cycle printed the number and subtracted 1 from count until count reached 0.THE TECHNICAL NAME
TAKEAWAY
while loop repeats as long as its condition stays True.6.2Repeating Over Sequences (for & range)
Think of stepping down a flight of 5 stairs — you know exactly how many steps you need to take.
SHOW:
WHAT HAPPENED HERE
range(1, 4) generated numbers 1, 2, and 3. The for loop assigned each number to variable i one by one.THE TECHNICAL NAME
TAKEAWAY
for i in range(start, stop) to repeat code a set number of times.6.3Iterating Through Lists & Strings
Think of a teacher reading student names from an attendance sheet one by one.
SHOW:
WHAT HAPPENED HERE
for loop automatically pulled each element out of the names list in order and stored it in variable name.THE TECHNICAL NAME
TAKEAWAY
for item in collection: to process every element cleanly.6.4Loop Control (break & continue)
Think of line jumping at an amusement park: continue skips the current person, while break closes the ride completely.
SHOW:
WHAT HAPPENED HERE
num == 3, continue skipped the print line. When num == 5, break terminated the entire loop immediately.THE TECHNICAL NAME
TAKEAWAY
break to stop a loop and continue to skip an item.GOTCHA 1
Forgetting to update counter variables inside while loops, creating infinite loops that freeze execution.
GOTCHA 2
Off-by-one errors with range(start, stop) — remembering stop index is exclusive!
GOTCHA 3
Modifying list items while iterating over the exact same list.
WHERE THIS SHOWS UP IN REAL CODE
Games run infinite loops checking player inputs until Game Over, while servers loop over database records to generate reports.
TRY THIS YOURSELF
Write a for loop with range(1, 6) printing squares of each number.
Notice how while loop exits as soon as success becomes True.
for n in range(1, 8):
if n % 15 == 0: print("FizzBuzz")
elif n % 3 == 0: print("Fizz")
elif n % 5 == 0: print("Buzz")
else: print(n)current iteration → Fizz? no
What condition causes a while loop to stop running?
What numbers does `range(1, 5)` generate?
What does the `break` statement do inside a loop?
What does the `continue` statement do inside a loop?
What is an infinite loop?
What does `range(3)` generate?
How many times will `for x in [10, 20, 30]:` run?
What is an off-by-one error?
Can you iterate over characters of a string with a `for` loop?
# comments · loops
- @priya · 2h ago
The typewriter hero is such a nice touch.
- @alex · 1h ago
Totally agree! Made it super engaging.
- @sam · 1d ago
Finally a course where I can run code without leaving the page.