CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Build with Python

Debugging Like a Detective

Lesson 8 of 12 · 7 min · Free, no account needed

What you will learn

  • A logic error gives a wrong answer with no red message.
  • Print debugging: print the values at a point and compare them with what they should be.
  • Start with a hypothesis, then test it. The bug sits between the last right value and the first wrong one.
  • Probe the middle first and halve again: a few probes find a bug in a long program.

Start the lesson

How the lesson goes

  1. No red error. The game just says your average is 0.

    Run it and look at the output.

  2. Where do you think the bug is hiding?

    Tap the line you suspect. A hunch is fine.

  3. Test it with probes.

    Drag a probe into a gap. It prints the values there, next to what they should be.

  4. How detectives debug.

    A logic error is a bug with no error message: the program runs and gives the wrong answer.

    Print debugging: put print(...) between lines to see the values right there. A probe here is exactly that.

    Start with a hypothesis, then test it. The bug is between the last right value and the first wrong one. Probing the middle and halving finds it fast.

  5. Fewest probes: a 12-line program with one bug.

    A shopping total should be 28 and it prints 33. Four probes at most. Par is 3.

  6. Now fix the average.

    Tap the part of line 4 that's wrong, pick the fix, then Run.

  7. Add up 1 to 10. It should be 55. It says 45.

    Move the stop number of range until the total is right.

  8. An AI helper wrote this. It says it's tested.

    is_even(4) should be True and is_even(7) should be False. Run it, then fix it.

  9. The probes are already in. Which line is guilty?

    It should print True: the average 22 is above 21.

  10. File your cases.

    Drop each bug you caught today into its folder.

Previous lesson: Counting with a Dictionary · Next lesson: Functions That Call Functions · Part of the course: Build with Python

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab