Definition
The error message looks scary. What is it actually telling you?
An error is Python's report that it cannot continue. A syntax error means the code breaks Python's grammar and nothing runs. An exception happens while the code runs, such as dividing by zero. The traceback shows where the error happened, and its last line names the error type and explains it. Debugging is finding and fixing the cause.
In simple words
Read the traceback from the bottom up. The last line says what went wrong, such as NameError: name 'scor' is not defined. The line number above it says where. Most errors are small: a typo, a missing quote, or a number added to text.
Overview
- Errors are normal; reading them carefully is the fastest way to fix a program.
- A traceback shows the chain of calls, the file and line number, the error type and a message.
- Read a traceback from the bottom up: the last line names the error, the line above shows where it happened.
- Debugging is a cycle: reproduce the error, find the cause, fix it, then test again.
- Useful tools are print statements, trace tables, an IDE debugger and explaining the code aloud (rubber-duck debugging).
- The hardest errors are those with no message, where the program runs but gives a wrong answer.
Why it matters
Every programmer, at every level, spends much of their time debugging. Reading errors calmly turns them from a wall into a signpost, and is the fastest way to become independent.
Key terms
- Syntax error
- Code that breaks Python's grammar; nothing runs until it is fixed.
- Exception
- An error that happens while the program is running.
- Traceback
- Python's report showing the chain of calls that led to an error, ending with the error type and message.
- Logic error
- A bug where the program runs but gives a wrong result.
- Breakpoint
- A marked line where a debugger pauses the program so you can inspect variables.
- Minimal example
- The smallest piece of code that still shows the bug.
Types
Programming errors fall into a few main types. Knowing the type tells you where to look and how to fix it.
1. Syntax errors
Code that breaks Python's grammar rules, so the program cannot start at all.
- How it works: Python checks the whole file before running; it reports SyntaxError with a caret (^) near the problem, such as a missing colon, bracket or quote.
- Example: if marks > 33 print("Pass") fails because the colon after 33 is missing.
- When to use it: Fix these first; read the line shown and the line just before it, where the real mistake often is.
2. Indentation errors
A special syntax error caused by missing, extra or mixed spaces at the start of lines.
- How it works: Python uses indentation to decide which lines belong to a block, so it raises IndentationError or TabError when the spacing is inconsistent.
- Example: A line inside a for loop typed with no indentation gives "expected an indented block".
- When to use it: Prevent them by letting the editor insert four spaces for each level and never mixing tabs with spaces.
3. Runtime errors (exceptions)
Errors that happen while the program is running, when an operation cannot be done.
- How it works: Python stops and raises a named exception such as ZeroDivisionError, NameError, TypeError, ValueError, IndexError, KeyError or FileNotFoundError.
- Example: int("abc") raises ValueError; marks[10] on a list of 5 items raises IndexError.
- When to use it: Fix the cause where possible, and handle expected ones, such as bad user input, with try and except.
4. Logic errors
Mistakes in the reasoning: the program runs without any message but produces a wrong result.
- How it works: Python cannot detect them; you find them by testing with known answers, tracing values and checking boundary cases.
- Example: average = total / 3 when there are 4 subjects, or using > instead of >= for a pass mark.
- When to use it: Guard against them with test cases, trace tables and small assert checks inside the code.
Explained in detail
Reading a traceback from the bottom
A traceback can look frightening, but it has a fixed structure. Read the last line first: it names the error type, such as TypeError, and a message explaining it, such as "can only concatenate str (not "int") to str". The lines above show where it happened, as file names and line numbers, from the first call at the top to the line that actually failed at the bottom. In your own short programs, the line just above the last line usually points directly to the culprit. Since Python 3.11, tracebacks even underline the exact part of the line that failed.
Three kinds of bug
| Kind | When you notice | Example |
|---|---|---|
| Syntax error | Before anything runs | A missing colon after if |
| Runtime exception | When that line runs | int("twelve") raises ValueError |
| Logic error | Only by checking the output | Dividing by 10 instead of the number of marks |
Logic errors are the most dangerous because Python gives no warning. The only defence is testing: compare actual results with results you worked out by hand, especially for edge cases.
A debugging routine that works
- Read the whole error message slowly, especially the last line.
- Go to the line it names and the line just before it, since a missing bracket is often reported one line late.
- Print the values of the variables involved just before the failing line.
- Form a guess about the cause, change one thing and run again.
- If stuck, cut the program down to a minimal example that still fails.
Tools beyond print()
Editors such as VS Code include a debugger: you click beside a line to set a breakpoint, run in debug mode, and the program pauses there so you can inspect every variable and step forward one line at a time. Python also has a built-in breakpoint() function that does the same in a terminal. And when you search for help online, paste the exact last line of the traceback; someone has almost certainly met it before.
Above all, stay calm. Every programmer, including the most experienced, sees error messages every day. An error is not a judgement on you; it is Python telling you precisely where to look, which is far more helpful than a program that silently gives a wrong answer.
How it works
| Error | Usual cause | Example |
|---|---|---|
| SyntaxError | Broken grammar: missing quote, bracket or colon | print("hi) |
| IndentationError | Wrong spaces at the start of a line | An extra space before print |
| NameError | Using a name that doesn't exist, often a typo | print(scor) |
| TypeError | Mixing types that don't go together | 10 + "5" |
| IndexError | Asking for a position that doesn't exist | [1, 2, 3][5] |
| ZeroDivisionError | Dividing by zero | 10 / 0 |
- Read the last line of the traceback: what type, and what message?
- Go to the line number it names.
- Print the values of variables just before that line.
- Change one thing, run again, and see what changed.
In code
Each broken line is run inside try, so the program keeps going and prints the error type and message instead of stopping.
def show_error(description, broken):
try:
broken()
except Exception as error:
print(description, "->", type(error).__name__ + ":", error)
show_error("Typo in a name", lambda: print(scor))
show_error("Number plus text", lambda: 10 + "5")
show_error("Position 5 of a 3-item list", lambda: [1, 2, 3][5])
show_error("Dividing by zero", lambda: 10 / 0)Output
Typo in a name -> NameError: name 'scor' is not defined Number plus text -> TypeError: unsupported operand type(s) for +: 'int' and 'str' Position 5 of a 3-item list -> IndexError: list index out of range Dividing by zero -> ZeroDivisionError: division by zero
Try it yourself
Which error is this?
Match each broken line to the error Python reports.
- print("hello)
- age = 15; print(agee)
- "Score: " + 90
- marks = [70, 80]; marks[2]
- average = 100 / 0
Common mistakes
- Reading the traceback from the top and getting lost. Start at the bottom.
- Changing many things at once, so you don't know what fixed it.
- Ignoring the line number. It points straight at the problem, or just after it.
Check yourself
Summary
- Syntax errors stop the program before it runs; exceptions happen while it runs.
- Read the traceback from the bottom: type, message, line number.
- Debug by printing values and changing one thing at a time.
Finished reading?
Sources: Python docs: Errors and Exceptions