It is time for the big switch. Rocket and Raven write the new station report together. Raven reads each line out loud while Rocket types.
"Now the supplies live in one dictionary," Rocket says. "And one loop calls report for each one." Raven asks, "What do you notice about adding tape now?"
Rocket grins. "One new pair in the dictionary. That is it!" Nova glows with pride. "Great discovery! Let's check that the output still matches."
# Station report, version 2
low_line = 20
def total_of(amounts):
total = 0
for amount in amounts:
total = total + amount
return total
def report(name, amounts):
total = total_of(amounts)
print(name + ":", total)
if total < low_line:
print("Low on", name.lower())
supplies = {
"Water": [12, 9, 15],
"Oats": [4, 6, 2],
"Fuel": [40, 35, 50],
}
for name in supplies:
report(name, supplies[name])
print("Report done") | The screen shows |
|---|
| Water: 36 |
| Oats: 12 |
| Low on oats |
| Fuel: 125 |
| Report done |
The output matches version 1 line for line. The refactor worked.
| Question | Version 1 | Version 2 |
|---|---|---|
| Lines that add up a list | three loops | one loop, in total_of |
| To add tape | copy a whole chunk | add one pair to supplies |
| To change the low line | change 20 in three places | change low_line once |
| Change to version 2 | Would the output stay exactly the same? |
|---|---|
| Rename amount to a on both lines | ? |
| Change low_line to 10 | ? |
| Add a comment above report | ? |
def total_of(amounts):
total = 0
for amount in amounts:
total = total + amount
return total
shifts = {"Rocket": [2, 3], "Raven": [4, 1, 2], "Kai": [5]}
for name in shifts:
print(name, total_of(shifts[name])) | Statement | True or false? |
|---|---|
| total_of is written once and called three times. | ? |
| The loop visits each key in shifts. | ? |
| shifts["Raven"] is a number. | ? |
| Adding "Ada": [1, 1] adds one more screen line. | ? |
Week eleven is done, Crew Engineer! You traced, cleaned and tested a long program. Next week is launch day!