← Back to course
Code Crew G4 / Week 11 / Tuesday
2/6
Week 11 Β· Refactor

Tuesday

Spot the repetition
// Same output, cleaner code
⏱ about 15 min

Tuesday: Spot the repetition

The crew wants the report to cover tape too. Rocket copies the fuel chunk, pastes it at the bottom, and changes the names. When he runs it, Tape shows 125. That is the fuel number!

"What do you notice?" Raven asks, pointing at one line. Rocket groans. "I missed a name when I changed the copy."

Nova blinks thoughtfully. "Interesting! Would you like a hint? When code is copied again and again, every copy is a new place for a bug to hide."

Copy and paste bugs

The three chunks in the station report are almost the same. Only the names change.

Copying a chunk is fast, but it is easy to miss one name. Here is Rocket's tape chunk.

fuel = [40, 35, 50]
tape = [3, 1, 2]
fuel_total = 0
for n in fuel:
    fuel_total = fuel_total + n
tape_total = 0
for n in tape:
    tape_total = tape_total + n
print("Tape:", fuel_total)
The screen shows
Tape: 125
FIND THE BUG
  • Read the question.
  • Tap your answer.
Which line has the bug?
After the fix, what should the screen show?

What changes, what stays

Part of each chunkSame in every chunk?
total = 0, then a loop that addsyes
the list being addedno: water, oats or fuel
the label printedno: Water, Oats or Fuel
the check: is it under 20?yes
StatementTrue or false?
The three chunks do the same job with different data.?
Each chunk needs a different loop.?
The parts that change could become parameters.?
Copying chunks makes bugs less likely.?
WHY THIS EXERCISEThe parts that change become parameters. The parts that stay become the function body.
A function for one chunk needs a parameter for the label and one for the
Try it
Find something you do the same way every day, like packing a bag.
Which parts change from day to day? Which stay the same?

Practice lab: one more copy bug

shuttle = [5, 7]
rover = [2, 4]
shuttle_total = 0
for n in shuttle:
    shuttle_total = shuttle_total + n
rover_total = 0
for n in shuttle:
    rover_total = rover_total + n
print("Shuttle:", shuttle_total)
print("Rover:", rover_total)
What number does the Rover line show?
What number should the Rover line show?
Which list does the second loop visit?
FIND AND PLAN
  • Read the question.
  • Tap your answer.
Which line has the bug?
What changes from chunk to chunk?
A function for this chunk needs which parameter?
StatementTrue or false?
Both chunks have the same shape.?
The bug is a missed name in a copied chunk.?
A function would need a new loop for each vehicle.?
Fixing one copy fixes all the copies.?
WHY THIS EXERCISEWith a function, a fix in one place fixes every use.
The station has 6 supplies, each with a copied chunk of 5 lines. How many lines is that?
WHY THIS EXERCISEThirty lines means thirty places for a typo. A function shrinks that a lot.

Sharp eyes! Tomorrow you will turn the repeated chunk into a function.

← Monday