← Back to course
Code Crew G4 / Week 03 / Thursday
4/6
Week 03 Β· Loop through a list

Thursday

Count what matches
// Visit every item
⏱ about 15 min

Thursday: Count what matches

The cargo list is long and messy. Water crates are mixed in with oats, tape and tools. "How many water crates do we have?" Raven asks.

Rocket starts a loop that counts every item. It says 5. "That counts everything," Raven says gently. "What do you notice? We only want the water."

Nova scans the list and lights up each water crate in blue. "Would you like a hint? The loop can ask a question about each item before it counts."

A counter with a question

A counter starts at 0 and goes up by 1 each time something happens.

The if line asks a question. The == sign asks: are these the same?

The counting line is indented under the if, so it only runs when the answer is yes.

cargo = ["water", "oats", "water", "tape", "water"]
count = 0
for item in cargo:
    if item == "water":
        count = count + 1
print("Water crates:", count)
The screen shows
Water crates: 3
SignWhat it meansExample
=store a valuecount = 0
==ask if two values are the sameitem == "water"
Change the if line to if item == "tape":. What number shows after Water crates: now?
WHY THIS EXERCISEThe if decides what gets counted. The label is only a string, so it does not change.
LineDoes it ask a question (instead of storing)?
if item == "oats":?
count = 0?
if name == "Raven":?
total = total + 5?
WHY THIS EXERCISEMixing up = and == is a very common bug. Now you can spot it.
launches = ["go", "wait", "go", "go", "wait", "go"]
ready = 0
for s in launches:
    if s == "go":
        ready = ready + 1
print(ready)
What number does the program above show?
WHY THIS EXERCISEA counter with an if lets a program count only what matters.
Try it
Look at the words in this sentence: the cat sat on the mat.
Count how many times the word the appears. You are the loop!

Practice lab: count the lows

log = ["ok", "low", "ok", "ok", "low"]
lows = 0
for x in log:
    if x == "low":
        lows = lows + 1
print("Low:", lows)
What number shows after Low:?
If the if line said x == "ok", what number would show?
How many times does the loop run?
COUNTER CHECK
  • Read the question.
  • Tap your answer.
Which sign asks if two values are the same?
lows = lows + 1 is indented under the if. When does it run?
What does a counter start at?
StatementTrue or false?
if x == "low": asks a question.?
lows = 0 asks a question.?
The counter goes up by 1 for each match.?
A counter adds up the values in the list.?
WHY THIS EXERCISECounters count matches. Running totals add values. Both use a loop.
cups = ["red", "blue", "red", "red"]. A loop counts the items equal to "red". What is the count?
WHY THIS EXERCISEThe counter grows only when the if is true.

Great counting! Tomorrow you will debug some loops that went wrong.

← Wednesday