Skip to content
Exit presentation

Computational Thinking III: Functions & Debugging

A print in the middle

A program can print a wrong fare with no error message.

Three lines run. Nothing says which is wrong.
Step 1 of 4
  1. Three lines run. Nothing says which is wrong.
  2. Add print(off); after the let off line.
  3. The window shows off = 6.
  4. It should be 4. Look at the let off line.

Pick where to put a print below. Read what it shows.

Loading lab…

The rule

A print in the middle shows what a box held right then. That is often not what you assumed. Printing changes nothing else about the run. So a print works as a window. It lets you see inside a box.

A group pays 2 rupees less for each rider after the first. Three riders travelling three stops should cost 20. The call is groupFare(3, 3).

`` function groupFare(riders, stops) { let one = 2 + 2 * stops; let off = 2 * riders; return one * riders - off; } ``

The box one is the fare for one rider. It is 2 + 2 × 3 = 8. This prints 18, because 8 × 3 − 6 = 18. Add print(off); after the let off line. It shows 6. Two riders get the discount, so off should be 2 × 2 = 4. Then 8 × 3 − 4 = 20.

  • Print the box, not a guess.
  • Print one thing, near the line you doubt.
  • Take the prints out when you are done.

Jump to lesson

This track

  1. 0 Start here
  2. 1 A name for a group of steps
  3. 2 What you hand it, and what each end is called
  4. 3 The value it hands back
  5. 4 One call inside another
  6. 5 A print in the middle
  7. 6 One line at a time
  8. 7 Predict, then run
  9. 8 Halve the hunt
  10. 9 The big picture
  11. 10 Track quiz

Other tracks