Debugging – Guidelines and Tools

Programs have bugs. Very few people write code that has no bugs when they first run it. 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! Bugs are also introduced to correct code when it is changed or used in a different application. The first step to ensuring code runs as intended is to learn how to write good code. Here are some guidelines to follow:

  • Learn the syntax and indentation rules. Python has few rules compared to other languages.  If you are not sure how to correct a syntax error, look up the rules.
  • Use environments like Canopy which will pop up a help window while you are typing (e.g., after typing “range(” a window will tell you the rules of range and how to use it).
  • Don’t copy code from Word processing files. Copying a single statement may be okay unless the statement contains quotes.
  • Comment your code. It is surprising how quickly one forgets!
  • Write code incrementally. Write small portions (often functions) and make sure they contain no errors and execute as intended. This may require you to think about creating special test cases.
  • To find all bugs, you will need to think through the code.  That is the only way one avoids fixing one bug and in the process introducing two more.

Here is a list of what causes errors and distress when learning how to program (Experience from teaching high school)

  • Misspellings. For example of variable names, reserved words, function names.
  • Not following the syntax rules. Includes missing colons, incorrect indentation, double equal versus equal, ….
  • Incorrect use of range.
  • Incorrect boundary conditions. For example, beginning of loop, end of loop, entry to module, exit from module, value less than limit (instead of less than or equal), table overflow, or table empty. Always check that the boundary conditions are what they need to be.
  • Not finding where the code is saved; not saving previous versions of the code.

Debugging tools are programs used to test and debug program. They typically allow one  to run a program interactively while watching the source code and the variables during the execution.  Python offers some very simple to use debugging tools and more sophisticated ones.  We discuss three debugging tools: