π Debugging Errors
Code not working? Follow the steps in the debugging process below before asking a peer or your teacher! Fixing your own errors, no matter how small, is one of the best ways to become a better coder.
π Python Debugging Process
-
Read the Error Message
- Look at the bottom line of the traceback β thatβs the actual error type (e.g.,
NameError,IndentationError,TypeError). - Read the line number the error happened on and the line above it, too.
- Look at the bottom line of the traceback β thatβs the actual error type (e.g.,
-
Check Your Spacing and Indentation
- Make sure every indent is exactly 4 spaces, not tabs.
- Blocks like
if,for,while,def, andclassmust be followed by a colon (:) and indented on the next line. - Every nested block should line up vertically.
-
Check Your Capitalization
- Python is case-sensitive.
print,Print, andPRINTare all different! - Be consistent with how you spell variable names, functions, and keywords.
- Python is case-sensitive.
-
Check Spelling and Naming
- Misspelled variable? Function name? Python wonβt guess β you must match exactly.
- Watch for typos like
pritninstead ofprint.
-
Check Symbols and Syntax
- Strings must be inside quotes:
"Hello"or'Hi' - Use
==for comparison, not= - Colons (
:) afterif,for,while,def, andclass - Matching parentheses
(), brackets[], and braces{}
- Strings must be inside quotes:
-
Print Often
- Add
print()statements to check what your variables contain. - Print just before the line that crashes to see whatβs going on.
- Add
-
Run Small Pieces at a Time
- Donβt write 50 lines and then run. Test after every few lines.
- Break big problems into small chunks and test each one.
-
Use Meaningful Variable Names
- This makes it easier to track your logic and avoid confusion.
-
Ask Yourself Questions
- What is this line trying to do?
- What type is this variable? (
int,str,listβ¦) - Should this function return something? Is it?
-
If All Else Failsβ¦
- Comment out sections of your code and slowly re-enable them.
- Use a visualization tool like PythonTutor.com to βstep throughβ code, which shows whatβs happening line-by-line.