Skip to content

Instantly share code, notes, and snippets.

@brianspiering
Last active July 20, 2023 16:57
Show Gist options
  • Save brianspiering/c43fc94ee7eb0da622a4deaf5eb8f185 to your computer and use it in GitHub Desktop.
Save brianspiering/c43fc94ee7eb0da622a4deaf5eb8f185 to your computer and use it in GitHub Desktop.
Debugging advice for programming

What to do when your code doesn't work

Follow these steps:

  1. Don't Panic! Relax and realize that you will solve this problem, even if it takes a little bit of messing around. Banging your head against the computer is part of your job (both as a student and as a professional programmer). Remember that the computer is doing precisely what you are telling it to do. There is no magic.

  2. Determine precisely what is going on. Did you get an error message from Python? If it is a SyntaxError, a helpful guide is here. Also, running your code in Python 3.11 or higher has improved error messages.

  3. Python error messages include a stack trace. There could be a number errors throughout the stack. You read a stack trace from bottom to top. Go slowly and understand each character and each line.

    Given this Traceback:

    "abc".uppre()
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-2-a2268f9e2941> in <module>
    ----> 1 "abc".uppre()
    
    AttributeError: 'str' object has no attribute 'uppre'

    I misspelled upper() as uppre().

  4. If it does not look like it is some simple mistyping, you might get lucky and find something in Google if you copy and paste the error message.

  5. If your code is running without errors, then insert print statements to figure out what the variables are at different points. That often tells you what the problem is. Something like this often works:

    print(f"Expected {foo}. But actually got {bar}.")
  6. You get the most learning by trying to solve the problem completely on your own but don't waste too much time (~15 minutes at the upper end). You should seek external help. Options include ChatGPT, Stack Overflow, a peer, a senior team member, or an instructor.

Other resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment