"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 stepping-stone numbers
1 Argument: range(stop)
range(5)
0, 1, 2, 3, 4
Starts at 0, stops before 5
2 Arguments: range(start, stop)
range(2, 7)
2, 3, 4, 5, 6
Starts at 2, stops before 7
3 Arguments: range(start, stop, step)
range(0, 10, 2)
0, 2, 4, 6, 8
Leaps by 2, stops before 10
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 & Stepping Stones Explorer
Woodland Stepping Stones Generated by range():
Configure range and click Run
COMPARISONFor Loop vs. While Loop — Which Should You Choose?+ Explore
# For Loop - when you know how many times
for ii in range(5):
print(ii)
# While Loop - when you don't know ahead of time
counter = 0
while counter < 5:
print(counter)
counter += 1
Mental Model: A for loop is like a ticket dispenser that counts automatically. A while loop is best when the stopping condition depends on changing events.
CHEAT SHEETCommon for & range() Loop Patterns+ Explore
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)
Woodland Milestone: You've crossed the stepping stones of for and range()! Next, let's package reusable spells into Functions.