Topic: Learning notes
MIT 6.100L Lecture 3: Iteration
Study notes for MIT OpenCourseWare 6.100L Lecture 3, covering while and for loops, range, control flow, approximation, and iteration patterns.
Iteration is like putting your intent into a metronome: as long as a condition holds, or as long as there is another element, it keeps ticking. MIT 6.100L Lecture 3 uses very human examples to lock in the intuition for while and for: the Lost Forest, Netflix binge-watching, factorials, running sums. This article organizes them into actionable mental models, plus a few engineer-proofing habits.
The shortest path to learning loops
Do not memorize syntax. Ask one question first: “Am I waiting for a condition to change?” Or “Am I walking through a sequence?”
The first is almost always
while; the second is almost alwaysfor.
1) while: condition is king, and also the easiest way to summon a black hole
while is pure in meaning:
As long as the condition is True, execute the block; after each execution, check again.
So it is great for tasks where you do not know how many times to repeat: waiting for correct input, waiting for a state to change, waiting for data to arrive (and also the easiest way to write an endless loop).
Lost Forest in Python (with case guard)
where = input("Go left or right? ")
# Normalize to lowercase to avoid RIGHT/Right mismatches
where = where.strip().lower()
while where == "right":
where = input("Go left or right? ").strip().lower()
print("You got out of the Lost Forest!")
Note: two common ways infinite loops happen
- The condition never changes: you did not update any variable tied to the condition.
- The condition does change, but you do not notice: case, whitespace, or type (string vs number) skews the check.
2) Netflix’s “Are you still watching?” is a while thought experiment
Lecture 3 uses Netflix binge-watching as a metaphor: as long as there is another episode and you are still interacting, it keeps playing; if you fall asleep or it finishes, the condition turns False, the loop stops, and it prompts you.
You can think of it as:
- State:
still_has_episode,user_is_active - Loop: as long as both hold,
play_next_episode()
The key is not Netflix, but learning to think in “state + condition” when you control flow.
3) for: elegantly walk a sequence (especially range)
When what you want is really “do N times” or “walk a slice of integers,” for is almost always cleaner:
# while version (you maintain n yourself)
n = 0
while n < 5:
print(n)
n += 1
# for version (let range manage how n changes)
for n in range(5):
print(n)
range(start, stop, step): stop is not included, by design
You benefit in a lot of places:
- Align with indices:
range(len(arr))yields valid indices - Avoid printing one extra: stop is excluded, so boundaries are consistent
- Walk backwards:
range(4, 0, -1)is intuitive for countdowns
Note: the easiest rule to remember
range(5)yields[0,1,2,3,4]. Python is not messing with you, it is helping you: this aligns with valid indices for a sequence of length 5.
4) Running sum: turn accumulation into loop muscle memory
Running sum is one of the best patterns to master early: you will see it again and again in stats, data processing, and algorithms.
mysum = 0
for i in range(10): # i: 0..9
mysum += i
print(mysum) # 45
Tip: inner narration (surprisingly effective)
On each iteration, say one sentence: “What is i now? What is mysum now? What does this round add?” This is basically moving Python Tutor’s visualization into your head.
5) Factorial: while vs for on readability
Factorial is a classic: n! = 1 x 2 x ... x n
# while version: you manually advance i
x = 4
i = 1
factorial = 1
while i <= x:
factorial *= i
i += 1
print(f"{x} factorial is {factorial}")
# for version: no "advance i" bookkeeping
x = 4
factorial = 1
for i in range(1, x + 1):
factorial *= i
print(f"{x} factorial is {factorial}")
Note: the pragmatic takeaway
Whenever you are iterating a well-defined sequence (like 1..n),
forusually has fewer failure modes;whileshines when you are waiting for a state change or the count is unknown.
6) Loop control: break, continue, and the “lazy-looking” pass
Three keywords, three different flow gestures:
break: exit the loop (emergency exit)continue: skip this round and go to the next (ignore a case)pass: do nothing (syntax placeholder)
Example: input validation (with while-else)
correct_password = "magic123"
attempts = 0
while attempts < 3:
pwd = input("Enter password: ")
if pwd == correct_password:
print("Welcome!")
break
else:
print("Wrong password, try again.")
attempts += 1
else:
# Only runs if the loop was not interrupted by break
print("Too many failed attempts. Account locked!")
Tip: while-else is actually elegant
It cleanly separates “finished normally” from “broken early”: break = you leave early; else = you walk to the natural end.
Example: filter data with continue (one less nested if)
numbers = [4, -2, 0, 7, -5, 3]
positives = []
for n in numbers:
if n <= 0:
continue
positives.append(n)
print("Positives:", positives) # [4, 7, 3]
7) Three iron rules for debugging loops (save half your pain)
- Write the loop invariant first: at the start of each round, what must be true? (e.g.,
mysumalways equals the sum of processed elements) - Check boundaries (off-by-one): do you want to include the end?
rangeexcludes stop, be crystal clear. - When you need visualization, use tools: Python Tutor shows every variable step by step and is a cheat code for beginners.
Further Reading (Targeted Reinforcement)
-
MIT OCW: Lecture 3: Iteration (page and exercises)
-
MIT OCW: Lecture 3 video resources (with transcript downloads)
-
YouTube: Lecture 3: Iteration (your link)
-
Python official tutorial: Control Flow Tools (range / for / while semantics and examples)
-
Python language reference: precise semantics of break (including loop-else behavior)
-
Real Python: Python while Loops (fuller coverage of use cases and pitfalls)
-
Python Tutor: step-by-step execution visualization (highly recommended)