Reading error messages and a small project
A Python traceback is read from the bottom: the last line names the error, and the line above the code shows where it happened.
A moth taped into a log book in 1947
Today most bugs are mistakes in the code, and Python is good at telling you about the ones it can detect. Beginners often see a red error as a verdict. It is closer to a delivery note: what went wrong, on which line, and in which piece of code. The trick is knowing where to look.
Read a traceback from the bottom up
total = 0
count = 0
print(total / count)Traceback (most recent call last):
File "main.py", line 3, in <module>
print(total / count)
~~~~~~^~~~~~~
ZeroDivisionError: division by zeroStart with the last line. ZeroDivisionError: division by zero gives the type of error and a short explanation. Then move up to the File line: the file name (the full folder path appears there on your computer; it is shortened to main.py here) and the line number, 3. The line under that is the code itself, and Python 3.12 marks the exact operation that failed with ^ under the / sign. Only after reading all three should you start changing things. When the error happens inside a function, the traceback lists every call on the way there, and the bottom-most File line is usually the one to look at first.
| Error | Usual cause | Example |
|---|---|---|
| SyntaxError | The line is not valid Python: missing bracket, colon or quote | print("hi" |
| IndentationError | Missing or uneven indentation | if x > 1: with no indented line |
| NameError | A name that does not exist yet, often a typo | pritn("hi") |
| TypeError | An operation on the wrong type | "Age: " + 15 |
| ValueError | Right type, impossible value | int("abc") |
| IndexError | Index past the end of a list or string | [1, 2][2] |
| KeyError | Key not in the dictionary | {"a": 1}["b"] |
| ZeroDivisionError | Dividing by zero | 5 / 0 |
A SyntaxError is different from the rest. Python finds it before running anything, so not even line 1 runs, and there is no "Traceback" header. All the others happen while the program runs, after the earlier lines have already done their work. When you expect a particular error, you can catch it with try and except, which the tutorial covers in its chapter on errors: Python tries the indented block, and if that error happens, it runs the except block instead of stopping.
print("before")
n = int("abc")
print("after")before
Traceback (most recent call last):
File "main.py", line 2, in <module>
n = int("abc")
^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'text = "abc"
try:
n = int(text)
except ValueError:
n = 0
print(n)0The hardest bugs give no message at all. A logic error is a program that runs and prints the wrong answer, like the grading program from the unit on if that gave 85 a C. Python cannot know what you meant. For these, go back to the trace table, or add temporary print lines that show the variables at each step, then remove them once the bug is found.
Small project: a pocket-money log
The project uses something from nearly every unit: a dictionary of spending, a function that returns a total, a for loop, an f-string and an if. Type it in, run it, then make it yours: change the items, add a category, or warn when any single item costs more than half the allowance.
def total(spent):
t = 0
for amount in spent.values():
t += amount
return t
allowance = 30000
spent = {"snacks": 4500, "bus card": 10000, "notebook": 2500}
used = total(spent)
left = allowance - used
for item, amount in spent.items():
print(f"{item}: {amount} won")
print(f"Spent {used}, left {left}")
if left < 15000:
print("Less than half left")snacks: 4500 won
bus card: 10000 won
notebook: 2500 won
Spent 17000, left 13000
Less than half leftBefore you change it, write a trace table for used and left, and predict what happens if you add a 6,000-won item. Then debug on purpose: delete the colon after the def line, misspell spent once, and divide used by zero. Read each traceback from the bottom before you fix it. Being able to break a program and mend it again is the real skill this course has been building.
| traceback | Python's error report; read it from the bottom |
| SyntaxError | Invalid code, found before anything runs |
| NameError | A name that does not exist, often a typo |
| TypeError | An operation on the wrong type of value |
| ValueError | The right type with an impossible value, such as int("abc") |
| logic error | Runs without a message but gives the wrong answer |
| try / except | Runs the except block instead of stopping when that error happens |
- Which line of a traceback names the kind of error?
- The first line
- The File line
- The last line
- The line with ^ marks
- Which error does
int("12a")cause?- TypeError
- ValueError
- NameError
- SyntaxError
- Which error does
pritn("hi")cause?- SyntaxError
- NameError
- TypeError
- No error
- A program prints line 1 and then stops with an error on line 2. Which kind of error cannot be the cause?
- SyntaxError
- NameError
- TypeError
- ZeroDivisionError
- What does this print?
try: x = 10 / 0 except ZeroDivisionError: x = -1 print(x) - What happens when this runs?
print("start") print(5 / 0) print("end")- It prints start and end
- It prints start, then stops with ZeroDivisionError
- It stops with ZeroDivisionError before printing anything
- It prints start, inf and end
- A program runs without any message but prints the wrong total. What kind of error is that?
- SyntaxError
- Logic error
- NameError
- IndentationError
- What does this print?
spent = {"a": 4500, "b": 10000} print(30000 - sum(spent.values())) - Put the lines of this small program in order so it prints the result below.Output
80.0 - Where is the bug? def avg(nums): return sum(nums) / len(nums), called with avg([]).
- sum of an empty list is an error
- len([]) is 0, so it divides by zero
- return cannot hold a division
- There is no bug
- "The error is on the line the message names, so the fix goes there." Often, but not always. In the functions unit, x = show_area(4, 3) followed by x * 2 stops with a TypeError on the x * 2 line, yet the real mistake is the print inside show_area that should have been a return. Read the line named, then ask where its values came from.
- "Wrapping everything in try/except fixes errors." It only hides them. Catch a specific error you expect, such as ValueError from int(input()), and handle it in a way that makes sense.
- "No error message means the program is correct." Logic errors run silently. Test with inputs where you already know the answer, including edge cases such as an empty list or a boundary age.
- Read a traceback from the bottom: error type, then file and line, then the marked code.
- SyntaxError stops the program before line 1 runs; other errors stop it partway.
- try/except handles an error you expect.
- Logic errors give no message: trace and test with known answers.
- Debugging means breaking and mending on purpose until messages feel ordinary.
Sources for this course (6)
- Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
- Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
- Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
- General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
- Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
- Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)
Checked: 2026-10-19