Lesson 7 of 26 · about 14 min
for loops and range
A for loop does something once for each item in a sequence. range() makes a sequence of numbers, and an accumulator builds up a result.
🧭 What you need first: Repeating with while
A teacher hands back 30 tests. For each test in the pile, they write the grade in the gradebook. They don’t need to check “are there still tests?” before each one; they just go through the pile, one by one, until it’s empty.
That’s a for loop: “for each thing in this collection, do this.” Use while when you’re waiting for something to happen. Use for when you have a known collection to go through.
Another way: dealing cards
Dealing a deck: for each card in the deck, give it to the next player. The deck decides how many rounds there are. You never need a separate counter.
Another way: a checklist
Packing for a trip with a list: for each item on the list, put it in the bag and tick it. When the list ends, you’re done.
Watch an accumulator grow
This adds up 1 + 2 + 3 + 4 + 5. Step through and watch i take each value while total builds up.
Watch the code run, one step at a time
- 1total = 0
- 2for i in range(1, 6):
- 3 total = total + i
- 4print("Sum:", total)
➜ yellow = the line about to run · ✓ = the line that just ran
The real words
- A for loop goes through a sequence one item at a time. The loop variable (
iabove) names the current item. - You can loop over many things:
for letter in "hello":gives one letter at a time. - range() makes number sequences:
| Code | Gives |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(0, 10, 2) |
0, 2, 4, 6, 8 |
range(5, 0, -1) |
5, 4, 3, 2, 1 |
The stop number is never included. It feels odd at first, but it means range(5) has exactly 5 numbers.
- The accumulator pattern: create a variable before the loop, update it inside, use it after. It works for sums, counts, products, longest word, and more.
- Nested loops: a loop inside a loop. The inner loop runs completely for every single round of the outer one. 3 outer × 4 inner = 12 total runs.
breakstops the loop early.continueskips to the next item.
Multiples of 3 or 5
Add up all the numbers below 100 that are multiples of 3 or 5 (like 3, 5, 6, 9, 10, 12…). Store the answer in total.
Draw a triangle with nested loops
Print this triangle, using a loop inside a loop (the inner loop prints one * at a time with end=''):
🧩 Order these lines to count how many letters in a word are vowels.
Use the arrows to put the lines in the right order, then check.
for letter in word:count = 0print(count)word = "banana"count += 1if letter in "aeiou":
What numbers does range(2, 8, 2) give?
Got it?
Finish the lesson to color it in on your map and collect its concept cards.
Did this lesson click?