๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 3 ยท Lesson 9 of 15

0% Exit to course

Module 3 ยท Reusable code and honest errors Lesson 9 of 15

Reading an error instead of fearing it

Learning objective

A traceback is a map, not a punishment: the last line names the error, and the line above it points at the file and line number where it happened.

The concept

A traceback is a map. Read it from the bottom: the last line names the error, the line above it gives the file and the line number where it happened, and everything above that is the path the program took to get there. ValueError: invalid literal for int() with base 10: "abc" means you tried to convert text that is not a number.

Four errors cover most of your first month. NameError โ€” you used a variable that does not exist, usually a typo. TypeError โ€” you mixed a string and a number. IndexError โ€” you asked a list for a position it does not have. IndentationError โ€” a block's spaces are wrong. None of them mean you are bad at this; they mean the program told you exactly which line to look at.

Python
value = "abc"
try:
    number = int(value)
except ValueError as e:
    print("Could not convert:", e)   # invalid literal for int()...

Common mistakes

The habit worth building now: read the LAST line first, look at that line number, and fix one thing at a time. The mistake is scrolling to the top of a long traceback, feeling lost, and rewriting the whole file โ€” which throws away working code and usually adds the same bug back.

Worked example

ValueError: invalid literal for int() with base 10: "abc" tells you exactly which conversion failed โ€” you passed text where a number was expected.

Your practice task

Break your own program in three different ways on purpose and write down, in one line each, what the traceback told you.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A traceback is a map. Read it from the bottom: the last line names the error, the line above it gives the file and the line number where it happened, and everything above that is the path the program took to get there.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.