← Back to course
Code Crew G4 / Week 11 / Monday
1/6
Week 11 Β· Refactor

Monday

Read a long program
// Same output, cleaner code
⏱ about 15 min

Monday: Read a long program

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."

Chunk by chunk

  1. Read the top chunk. It sets up the data.
  2. Read each middle chunk. Say in your own words what it does.
  3. Trace any loop with a trace table.
  4. Read the last chunk. Then write down the output.
# 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.

Roundnoats_total after the round
before the loopnone yet0
144
2610
3212
water_total after round 1
water_total after round 2
water_total after round 3
Only one Low on line shows. Which supply is it for?
WHY THIS EXERCISEReading the if in each chunk tells you which messages appear.
CHUNKS
  • Read the question.
  • Tap your answer.
How many chunks add up a list and check it?
Try it
Read the oats chunk out loud.
Explain it in one sentence to a grown-up.

Practice lab: a two-chunk program

# 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)
on after round 2
on at the end
total after round 3
total at the end
READ THE CHUNKS
  • Read the question.
  • Tap your answer.
Which line does Python skip?
What does the first chunk do?
How many chunks loop over the decks list?
StatementTrue or false?
A blank line changes the output.?
Each chunk has its own loop.?
A comment starts with #.?
The second chunk counts decks.?
WHY THIS EXERCISEKnowing what each chunk does is the first step of any refactor.
Suppose decks were [1, 1, 0, 0]. What number would follow Lights on in all:?
WHY THIS EXERCISEThe second chunk adds every value in the list.

You read a long program like a pro! Tomorrow you will look for the parts that repeat.