← Back to course
Code Crew G4 / Week 11 / Wednesday
3/6
Week 11 Β· Refactor

Wednesday

Make a function from a chunk
// Same output, cleaner code
⏱ about 15 min

Wednesday: Make a function from a chunk

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

Pull out the adding

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.

Pull out the whole chunk

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
What does report("Tape", [3, 1, 2]) show on its first line?
What does it show on its second line?
MATCH THE OUTPUT
  • Read the question.
  • Tap your answer.
Why check that the output still matches after a refactor?
Try it
Write a call to report for a new supply, like lamps.
Make up a list of three numbers and work out what it shows.

Practice lab: a champion function

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]))
What does line 8 show?
What does line 9 show?
What does line 10 show?
FUNCTION CHECK
  • Read the question.
  • Tap your answer.
What is the parameter of biggest_of?
How many times is the champion loop written?
What does biggest_of([7]) return?
StatementTrue 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.?
WHY THIS EXERCISESame output, less repeated code. That is a good refactor.
What does biggest_of([3, 18, 18, 2]) return?
WHY THIS EXERCISE18 wins in round 2, and the second 18 does not beat it.

You turned a chunk into a function! Tomorrow you will make the code easier for people to read.

← Tuesday