Skip to content
Lesson 9 of 10 · Python for Complete Beginners

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.

code4 lines
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.

ErrorUsual cause
SyntaxErrora missing colon, bracket or quote
IndentationErrorblocks not lined up
NameErrora name that was never created (typo?)
TypeErrorthe wrong type: "5" + 5
ValueErrorright type, bad value: int("abc")
IndexErrorlist index past the end
KeyErrordictionary key not found
ZeroDivisionErrordividing by zero

When you expect something might fail, catch it instead of crashing:

python4 lines
try:
    age = int(text)
except ValueError:
    age = 0

Name 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:

python6 lines
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.

Exercise6 checks
python

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
starter code2 lines
def safe_int(text, default=0):
    pass
Exercise1 case
python

Write 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:

code3 lines
1. buy milk
2. call mom
3. study python

Your code must satisfy

  • numbered list
starter code2 lines
tasks = ["buy milk", "call mom", "study python"]
# write them to todo.txt, then read the file back and print
Steps
0/5

How to read an error you have never seen.

  1. Go to the last line

    The error type and message tell you what kind of problem it is.

  2. 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.

  3. Say it in plain words

    KeyError: "age" means "I asked the dictionary for age and it is not there".

  4. Print the suspect values

    Add print(value, type(value)) just before the failing line to see what is really there.

  5. 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.
Check yourself

Error checks.

1Multiple choice

int("hello") raises which error?

  • ATypeError
  • BValueError
  • CNameError
  • DIndexError
2Multiple choice

[1, 2, 3][3] raises which error?

  • AKeyError
  • BIndexError
  • CValueError
  • DZeroDivisionError
3Multiple choice

Where do you look first in a traceback?

  • AThe first line
  • BThe last line
  • CThe middle
  • DThe blank line
4Multiple choice

Which mode of open() erases an existing file and starts fresh?

  • A`"r"`
  • B`"w"`
  • C`"x"`
  • D`"e"`
5Fill the blanks

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.