Errors and files
Read a traceback, handle failures with try/except, and read and write a text file.
18 min
Every programmer sees errors all day. The skill is reading them. When Python crashes it prints a traceback: read it from the bottom.
Traceback (most recent call last):
File "main.py", line 3, in <module>
age = int(text)
ValueError: invalid literal for int() with base 10: 'abc'The last line is the type of error and what went wrong (ValueError). The lines above show where: file, line number, and the line itself.
| Error | Usual cause |
|---|---|
SyntaxError | a missing colon, bracket or quote |
IndentationError | blocks not lined up |
NameError | a name that was never created (typo?) |
TypeError | the wrong type: "5" + 5 |
ValueError | right type, bad value: int("abc") |
IndexError | list index past the end |
KeyError | dictionary key not found |
ZeroDivisionError | dividing by zero |
When you expect something might fail, catch it instead of crashing:
try:
age = int(text)
except ValueError:
age = 0Name the error you expect. A bare except: hides real bugs.
open() gives a file you can read or write. Use with, which closes it for you:
with open("notes.txt", "w") as f: # "w" writes (and replaces)
f.write("first line\nsecond line\n")
with open("notes.txt") as f: # "r" reads (the default)
for line in f:
print(line.strip())In this course your code runs in your browser, so a file exists only in a private space for the run: write it and read it back in the same program, but do not expect it to be there tomorrow. On your own computer the same code saves real files.
try, except, else and finally: only try and except are needed.
Write safe_int(text, default=0) that converts text to an integer and returns default when it cannot, instead of crashing. Spaces around the digits are fine.
Your code must satisfy
- safe_int("42")→42digits
- safe_int(" 7 ")→7spaces
- safe_int("4x")→0letters
- safe_int("")→0empty
- safe_int("3.5", -1)→-1custom default
- safe_int("-8")→-8negative
def safe_int(text, default=0):
passWrite the three lines buy milk, call mom and study python into a file called todo.txt, one per line. Then read the file back and print each line with its number, like this:
1. buy milk
2. call mom
3. study pythonYour code must satisfy
- numbered list
tasks = ["buy milk", "call mom", "study python"]
# write them to todo.txt, then read the file back and printHow to read an error you have never seen.
Go to the last line
The error type and message tell you what kind of problem it is.
Find your line number
The line above the message shows the exact line that failed. Look there first, and also at the line before it: a missing bracket often reports on the next line.
Say it in plain words
KeyError: "age"means "I asked the dictionary forageand it is not there".Print the suspect values
Add
print(value, type(value))just before the failing line to see what is really there.Change one thing, run again
Fix one cause at a time so you know which change worked.
- Read a traceback from the bottom: the error type, then the line number.
- Catch the specific error you expect with
try/except ValueError:. - Use
with open(...) as f:so the file is closed for you;"w"replaces,"r"reads. - In the browser, files live only for the run; on your own computer they are saved for real.
Error checks.
int("hello") raises which error?
- ATypeError
- BValueError
- CNameError
- DIndexError
[1, 2, 3][3] raises which error?
- AKeyError
- BIndexError
- CValueError
- DZeroDivisionError
Where do you look first in a traceback?
- AThe first line
- BThe last line
- CThe middle
- DThe blank line
Which mode of open() erases an existing file and starts fresh?
- A`"r"`
- B`"w"`
- C`"x"`
- D`"e"`
The block that runs when the try block fails is called .
Capitalisation, spacing and punctuation are ignored when grading.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.