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 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 |
| Sign | What it means | Example |
|---|---|---|
| = | store a value | count = 0 |
| == | ask if two values are the same | item == "water" |
| Line | Does it ask a question (instead of storing)? |
|---|---|
| if item == "oats": | ? |
| count = 0 | ? |
| if name == "Raven": | ? |
| total = total + 5 | ? |
launches = ["go", "wait", "go", "go", "wait", "go"]
ready = 0
for s in launches:
if s == "go":
ready = ready + 1
print(ready) log = ["ok", "low", "ok", "ok", "low"]
lows = 0
for x in log:
if x == "low":
lows = lows + 1
print("Low:", lows) | Statement | True 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. | ? |
Great counting! Tomorrow you will debug some loops that went wrong.