Read the whole message
An error message usually tells you three things: the type of error, a description, and where it happened. In Python:
Traceback (most recent call last):
File "main.py", line 4, in <module>
total = price * quantity
NameError: name 'quantity' is not defined
Read from the bottom up. The last line says what went wrong (a variable named quantity does not exist), and the line above it shows exactly where. In this case the variable was never created, or it was spelled differently.
Common errors and what they mean
- SyntaxError: the code breaks the language's grammar, such as a missing bracket, quote or colon. Check the reported line and the line before it.
- NameError (Python) / ReferenceError (JavaScript): you used a name that does not exist. Look for typos and capital letters:
Totalandtotalare different names. - TypeError: an operation got the wrong kind of value, for example adding a number to text in Python, or calling something that is not a function in JavaScript.
- IndexError (Python): you asked for a list position that does not exist. A list of 3 items has positions 0, 1 and 2.
- "Cannot read properties of null" (JavaScript):
document.querySelectorfound nothing. Check the selector, and make sure the script runs after the element exists.
A debugging method that works
- Reproduce it. Find the exact steps or input that cause the problem.
- Locate it. Use the line number, or print values before and after the suspicious line with
print()orconsole.log(). - Explain it. Say out loud what each line should do. The moment your explanation and the code disagree is usually the bug. Programmers call this "rubber duck debugging".
- Change one thing. Make a single change, then run again. Changing several things at once makes it hard to know what fixed it.
- Check the edges. Test with an empty input, zero, a very large number and unexpected text.
When there is no error message
The hardest bugs give wrong results without crashing. This function should average a list, but returns the wrong answer:
def average(numbers):
total = 0
for n in numbers:
total = n
return total / len(numbers)
Printing total inside the loop shows it is replaced each time instead of added to. The fix is total += n. Writing down the answer you expect before running the code makes these bugs much easier to spot.
Asking for help well
Whether you ask a teacher, a forum or an AI assistant, include: what you expected, what happened instead, the full error message, and the smallest piece of code that shows the problem. You will often find the bug yourself while preparing the question. See learning to code with AI for how to get explanations rather than just answers.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].