"For loops allow us to continuously change the value of a loop variable. Best for repeating a certain number of times."
Understanding Range
range() generates a sequence of numbers
range(5)
0, 1, 2, 3, 4
Starts at 0, stops before 5
range(2, 7)
2, 3, 4, 5, 6
Starts at 2, stops before 7
range(0, 10, 2)
0, 2, 4, 6, 8
Step by 2 each time
Critical Detail: range() is non-inclusive - it stops BEFORE the end number. If you want numbers 1-10, use range(1, 11).
How For Loops Work
for ii in range(5):
print(ii)
What's happening:
# Iteration 1: ii = 0
0
# Iteration 2: ii = 1
1
# Iteration 3: ii = 2
2
# Iteration 4: ii = 3
3
# Iteration 5: ii = 4
4
Interactive For Loop Explorer
Configure range and click Run
For Loop vs While Loop
# For Loop - when you know how many times
for ii in range(5):
print(ii)
# While Loop - when you don't know
counter = 0
while counter < 5:
print(counter)
counter += 1
# Same output, different use cases!
"For loops are cleaner when you know the count. While loops are better when the condition might change in unpredictable ways."
Mental Model: A for loop is like a ticket dispenser. You know exactly how many tickets (iterations) you'll get. The machine automatically counts for you.
Common For Loop Patterns
Count to N: for ii in range(n)
Count from A to B: for ii in range(a, b)
Count by steps: for ii in range(0, 10, 2) # evens
Countdown: for ii in range(10, 0, -1)
[####################..........] 10/15
> [WHY_IT_MATTERS]:
Iterating is visiting every house in the village. You don't miss a single one.