Rocket finds an old program in the station files. It is called the station report, and it is almost thirty lines long. "Whoa," he says. "Where do I even start?"
Raven scrolls through it slowly. "What do you notice about the blank lines? They split it into chunks, like paragraphs in a book."
Nova shines a soft light on the first chunk. "Would you like a hint? Read one chunk at a time. Keep a trace table as you go."
# Station report, version 1
water = [12, 9, 15]
oats = [4, 6, 2]
fuel = [40, 35, 50]
water_total = 0
for n in water:
water_total = water_total + n
print("Water:", water_total)
if water_total < 20:
print("Low on water")
oats_total = 0
for n in oats:
oats_total = oats_total + n
print("Oats:", oats_total)
if oats_total < 20:
print("Low on oats")
fuel_total = 0
for n in fuel:
fuel_total = fuel_total + n
print("Fuel:", fuel_total)
if fuel_total < 20:
print("Low on fuel")
print("Report done") | The screen shows |
|---|
| Water: 36 |
| Oats: 12 |
| Low on oats |
| Fuel: 125 |
| Report done |
The line that starts with # is a comment. It is a note for people, and Python skips it.
| Round | n | oats_total after the round |
|---|---|---|
| before the loop | none yet | 0 |
| 1 | 4 | 4 |
| 2 | 6 | 10 |
| 3 | 2 | 12 |
# Deck lights check
decks = [3, 0, 5, 2]
on = 0
for d in decks:
if d > 0:
on = on + 1
print("Decks with lights on:", on)
total = 0
for d in decks:
total = total + d
print("Lights on in all:", total) | Statement | True or false? |
|---|---|
| A blank line changes the output. | ? |
| Each chunk has its own loop. | ? |
| A comment starts with #. | ? |
| The second chunk counts decks. | ? |
You read a long program like a pro! Tomorrow you will look for the parts that repeat.