Python Errors & Tracebacks
A traceback is the report that follows an exception. The last line of a traceback names the problem.
A syntax error stops the start
This line is missing its closing bracket.
print("Hello"An exception happens while running
This code starts fine. It fails when it tries to divide.
print("Start")
print(10 / 0)Read the last line first
The name age was never made. The last line says so.
name = "Ada"
print(age)A value that does not fit
The text abc cannot become a whole number.
print(int("abc"))Example
print("Ticket shop")
price = 10
count = 0
print(price / count)Key points
- Syntax error: the code breaks the rules, so it will not start
- Exception: an error that happens while the code is running
- Traceback: the report that follows an exception
- Use the last line of a traceback to name the problem
In this example, you break one small shop program three ways. First, you leave off a closing bracket in a print line. Python reports a SyntaxError and the program never starts. Next, you fix the bracket but spell the name prce by mistake. Python starts, then reports a NameError for prce. Last, you fix the name and leave count set to zero. The code above shows this third try. It prints Ticket shop, then tries to divide by zero. The last line reports ZeroDivisionError: division by zero. Reading each last line told you what to fix next.
Note
A syntax error stops the whole file.
Even correct lines before it never run.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
You run a program and Python prints a long traceback. Where should you look first?