M&C6: Debugging Loops

Programs have bugs. What you want your program to do, is not always what it does. When writing code, the goal should be to find mistakes early. When one finds a mistake, the goal should be to fix it in an effective and permanent way. Fixing one mistake, but introducing two others in the process leads to a nightmare!

At the time loops are taught and used, it is a good idea to give students guidelines on how to debug programs with loops, how to interpret error messages, and how to handle common errors. Below are some guidelines.

  • Ask students to trace through the loops and to visualize the values of the variables during the execution (use print statements). This is most effective for small programs.
  • Print statements provide a record of the history of the execution. Common errors like “list index out of range” caused by incorrect use of the range function can often be detected by adding print statements. However, too much output generated by print statements can be overwhelming.
  • Teach your students how to use PythonTutor (http://pythontutor.com)  to follow the execution.
  • Insist that students comment their code.
  • Most of all, encourage your students to think through their code.

Common problems during execution of a program

  • No output is produced. If the program produces no output, add print statement so you can trace what statements are actually executed and what the values of the variables are during the execution. Doing so will usually provide insight into the flow of execution and point towards the actual problem to fix. For small programs, use PythonTutor.
  • Stuck in an infinite loop. See discussion in M&C4.
  • Crashing with an error message. Python prints a message, provides the line of code where the error occurred, and stops execution. In some cases such an error is easy to fix; like when the student forgot to initialize a variable before using it, when the student mistyped a variable name, or when there is a division by zero. In other cases, finding the cause of the error can be a challenge. If one can’t find the error, add print statements to the program so one is better able to trace its execution. In larger programs, one should make sure that individual parts of code are tested before they are included into the larger program.
  • Generating the wrong results. The program may have a mistake that is easy to spot and fix, or it could have a serious logic problem.  Sometimes it helps to have someone else look at your program with a “fresh set of eyes.”