Nova scans five stars and measures how brightly each one glows. She saves the numbers in a list.
Rocket wants the total glow. He adds the numbers on his fingers and loses his place twice. "Argh, let me start again!"
"What do you notice about each step you take?" Raven asks.
Rocket thinks. "I do the same thing every time. I add the next number to my total."
Nova hums. "Here is a hint. When a step repeats, a loop can do it for you."
A for loop visits each item in a list, one at a time. A running total starts at 0. Each pass adds the next item.
glow = [4, 7, 2, 9, 3]
total = 0
for g in glow:
total = total + g
print(total) Output: 25
| Pass | g | total after the pass |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 7 | 11 |
| 3 | 2 | 13 |
| 4 | 9 | 22 |
| 5 | 3 | 25 |
This is a trace table. It shows the value of each variable after every pass. Engineers use trace tables to check their thinking.
A loop can also count. Put an if inside the loop. Add 1 only when the item matches.
glow = [4, 7, 2, 9, 3]
count = 0
for g in glow:
if g > 5:
count = count + 1
print(count) Output: 2
dist = [12, 5, 9, 14, 3]
total = 0
far = 0
for d in dist:
total = total + d
if d >= 10:
far = far + 1
print(total, far) | Statement | True or false? |
|---|---|
| The loop runs 5 times. | ? |
| far goes up by d each time. | ? |
| 14 is counted as far. | ? |
| print runs 5 times. | ? |
Nice tracing! You kept a running total like a real engineer. Tomorrow the loop makes choices with if, elif and else.