Monday, May 25, 2020

Python Debugging

This week's assignment was all about debugging.  Errors in programming are inevitable so it's important to learn how to begin to approach them while learning how to code.  We were provided with three different scripts and had to fix them so that they would all run correctly.
For this class most of our coding is done in Spyder.  When you run a script in Spyder, like all IDEs if it gets hung up on an error it will tell you with some kind of error message, like a traceback or syntax error.  Sometimes the easiest way to find a problem in your code is simply to run it and then see where the problem is.
Once mistakes such as misspellings or incorrect capitalization are cleared up then the program can run correctly. 
Another way to approach debugging is to use Spyder's debugger.  With this, you can work through the code line by line and see what is happening at each point.  This is a good way to identify an error where the code is running but not giving you the sort of output that you are expecting.

This script had eight bugs that needed to be teased out before it would properly run.

Sometimes, you might want to sidestep a bug entirely.  You can do this by adding in a "try" and except clause.  For this section of the assignment we had to identify that part of the code with an error and put it into a "try" clause.  This means that the code will be attempted, but if it cannot run it will turn to the except clause instead of simply breaking.  For the "except" clause I added in an error message that would identify what the problem was and print that out.  Afterwards, the code would continue as normal.
As you can see in Part A an error message is printed out from the "except" clause.  However, Part B runs without issue.


A Flowchart showing the try/except process


Bug fixing can be tedious but it's important to have different approaches to problem solving.  The more errors you fix, the easier it become to figure out other bugs in the future.

No comments:

Post a Comment