← Back to course
Code Crew G5 / Week 01 / Tuesday
2/6
Week 01 Β· Crew check

Tuesday

Loops that add up
// The tools you already have
⏱ about 15 min

Tuesday: Loops that add up

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 running total

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
Passgtotal after the pass
144
2711
3213
4922
5325

This is a trace table. It shows the value of each variable after every pass. Engineers use trace tables to check their thinking.

Change the list to glow = [6, 1, 8, 5]. What does the program print now?
WHY THIS EXERCISEThe loop adds each item once, so the total is the sum of the whole list.

Counting the items that match

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
USE THE COUNTING PROGRAM, BUT CHANGE THE LIST.
  • Read the question.
  • Tap your answer.
With glow = [6, 1, 8, 5, 10], what does it print?
With glow = [1, 2, 3], what does it print?
PUT THE LINES IN ORDER TO TOTAL A LIST.
  • ?for g in glow:
  • ?print(total)
  • ?glow = [6, 1, 8, 5]
  • ? total = total + g
  • ?total = 0
WHY THIS EXERCISEA program runs top to bottom, so each variable must exist before a line uses it.
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)
total after round 2
total at the end
far at the end
If the list had one more 10, what would far be?
TOTAL OR COUNT?
  • Read the question.
  • Tap your answer.
Which line runs every round?
What does far count?
Where must total = 0 go?
StatementTrue or false?
The loop runs 5 times.?
far goes up by d each time.?
14 is counted as far.?
print runs 5 times.?
WHY THIS EXERCISEIndents decide what repeats and what runs once.
Run the same program with dist = [10, 10, 1]. What is the first number it prints?
WHY THIS EXERCISE10 plus 10 plus 1 is 21. far would be 2.

Nice tracing! You kept a running total like a real engineer. Tomorrow the loop makes choices with if, elif and else.

← Monday