Rocket is ready to clean up the station report. "Let's build it!" he says. "One function, used three times."
He starts typing, then stops. "Wait. How do I know I did not break anything?" Raven smiles. "What do you notice about the output we wrote down on Monday?"
Nova saves the old output in a glowing box. "Would you like a hint? After a refactor, the output must match exactly. That is your test."
Every chunk adds up a list. That job becomes a function with one parameter: the list.
It returns the total, so the rest of the program can use it.
def total_of(amounts):
total = 0
for n in amounts:
total = total + n
return total
water = [12, 9, 15]
oats = [4, 6, 2]
print("Water:", total_of(water))
print("Oats:", total_of(oats)) | The screen shows |
|---|
| Water: 36 |
| Oats: 12 |
Water: 36 and Oats: 12 match Monday's output. The refactor did not change what the program does.
The whole chunk can be one function. Its parameters are the label and the list.
def total_of(amounts):
total = 0
for n in amounts:
total = total + n
return total
def report(name, amounts):
total = total_of(amounts)
print(name + ":", total)
if total < 20:
print("Low on", name.lower())
report("Oats", [4, 6, 2]) | The screen shows |
|---|
| Oats: 12 |
| Low on oats |
def biggest_of(amounts):
best = amounts[0]
for amount in amounts:
if amount > best:
best = amount
return best
print(biggest_of([12, 9, 15]))
print(biggest_of([4, 6, 2]))
print(biggest_of([40, 35, 50])) | Statement | True or false? |
|---|---|
| One function replaces three copied chunks. | ? |
| The function must be changed for each list. | ? |
| return best hands back the biggest number. | ? |
| A refactor should change the output. | ? |
You turned a chunk into a function! Tomorrow you will make the code easier for people to read.