Skip to content
Exit presentation

Computational Thinking III: Functions & Debugging

Predict, then run

Run it first, and you may believe what it printed.

Predict all three lines first: 2, 1, 0.
Step 1 of 4
  1. Predict all three lines first: 2, 1, 0.
  2. Run it. Line 1 matches: 2.
  3. Line 2 does not match: 0, not 1.
  4. Line 3 matches: 0. Only line 2 is wrong.

Predict each purse below. Then see what the program prints.

Loading lab…

The rule

Write down what each line should print, before you run it. Predict from the job, not from the program. The first line where they differ is the one to check.

A ticket costs 8 rupees. You buy one whenever you have at least 8. Three purses hold 20, 8 and 4 rupees. This program counts the tickets.

In the program, n counts the tickets. The box left is the money not yet spent. From the job, 20 rupees buys 2 tickets. 8 rupees buys 1. 4 rupees buys none. So the prediction is 2, 1, 0.

`` function tickets(money) { let n = 0; let left = money; while (left > 8) { n = n + 1; left = left - 8; } return n; } ``

A prediction copied from the code repeats its mistake.

The program prints 2, 0 and 0. Only the second printed line differs.

Here only one printed line is wrong. Sometimes many printed lines are wrong from one fault. Then the later lines only repeat it. Look for the cause of the first difference. Mend that, then run again.

The wrong test is left > 8 on line 4. A purse of exactly 8 should buy a ticket. So it must be left >= 8.

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