Debugging Code for the first time as a beginner

Have you ever been writing your own code or running someone else’s code, and everything seems fine and dandy?

Then, everything comes to a screeching halt, and your screen is just filled with lines of code and error messages.

That’s definitely happened to me, and it still freaks me out. So here’s a reminder to you (and me) on what to do to solve these issues (that does not involve chucking the computer out the window)

  1. KEEP CALM. Take a couple breaths, or even take a moment to step away. This can help ease the tension and put you in a better state of mind.
  2. Figure out what the error means. Google is my best friend, and I just copy the error and see what StackOverflow has to say. Sometimes the error is more complicated, so you might have to phone a friend, coworker, mentor. Don’t be afraid to reach out! It’s part of the process.
  3. print() the variables involved in the error right before the line of the error if possible. This will help see if the variable is empty, missing something important, or even completely wrong. I like to print using the format below so I can clearly see what is being printed.
    # troubleshooting
    print('------------------------------')
    print('This is variable', variable)
    print('------------------------------')
    
  4. Think of different ways the code could be affected. Could it be something in the data? Did something get modified in the previous lines? Are we testing a different case that was not previously accounted for while writing the script? You might have just found a bug vs ran it wrong. This was what I encountered when I inherited code from a previous coworker; it wasn’t that I didn’t know how to run her code, it was that the original code wasn’t robust enough for the new data I was running!
  5. Sleep on it. Sometimes a good night’s sleep is all you need to come up with a resolution.

Good luck and you can do this!

Some errors I’ve come across:

KeyError - this is when you’re trying to access a dictionary using a key that doesn’t exist in the dictionary. (basically, something doesn’t exist)