Find a course

Module 5: Functions, Errors, Files and ModulesLesson 12 of 1214 min

Errors, Files and Modules

Read tracebacks, handle exceptions with try and except, read and write text files safely with with open, and import modules such as math and random.

Step 1 of 14Learn

Reading a traceback

When something goes wrong while a program runs, Python raises an exception and prints a traceback:

Traceback (most recent call last):
  File "report.py", line 12, in <module>
    avg = average(scores)
  File "report.py", line 3, in average
    return sum(nums) / len(nums)
ZeroDivisionError: division by zero

Read it from the bottom up. The last line names the exception type and describes it: here, a division by zero. The lines above show the path that led there: line 12 called average, and line 3 inside average failed. The deepest call, closest to the error, is listed last.

So the story is: average was called with an empty list, len(nums) was 0, and dividing by it failed. Now you know where to look and what to fix.

The exceptions you'll meet most often:

ExceptionTypical cause
NameErrormisspelled or undefined variable
TypeErrorwrong type, e.g. "3" + 4, or wrong number of arguments
ValueErrorright type, bad content, e.g. int("abc")
IndexErrorlist index past the end
KeyErrordictionary key that doesn't exist
AttributeErrormethod that doesn't exist for that type, e.g. 5.upper()
FileNotFoundErroropening a file that isn't there

Paste the last line of a traceback into a search engine and you'll usually find the explanation within seconds.

Step 2 of 14Practice · Diagram

Reading the traceback bottom-up

Tap the line that names the exact place the error happened.

Tap the shape that answers the question, then press Check.

Reading the traceback bottom-upProcess diagram: ZeroDivisionError → line 3, in average → line 12, in <module> → Story: empty list passed.ZeroDivision-Errorline 3, inaverageline 12, in<module>Story: emptylist passed
ZeroDivisionError

Read first: what went wrong.

line 3, in average

Where it failed: the deepest call.

line 12, in <module>

Who called it: the top-level script.

Story: empty list passed

len(nums) was 0, so the division failed.

Step 3 of 14Practice · Match the pairs

Match each line of code to the exception it raises.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. int("twelve")
  2. [1, 2, 3][3]
  3. {"a": 1}["b"]
  4. "Total: " + 5
  5. 10 / 0

Step 4 of 14Learn

Handling errors with try and except

Some errors aren't bugs in your code; they're things that can go wrong in the world: a user types letters instead of a number, a file is missing, a network is down. Instead of crashing, a program can catch the exception and respond:

try:
    qty = int(input("Quantity: "))
    print(f"Total: {qty * 4.5:.2f}")
except ValueError:
    print("Please enter a whole number.")

Python runs the try block. If a ValueError happens anywhere inside it, Python jumps straight to the matching except block instead of crashing. If nothing goes wrong, the except block is skipped.

Combined with a loop, this gives robust input handling:

while True:
    try:
        qty = int(input("Quantity: "))
        break
    except ValueError:
        print("That wasn't a whole number. Try again.")

Guidelines for using it well:

  • Catch specific exceptions, like ValueError or FileNotFoundError. A bare except: catches everything, including typos in your own code and the Ctrl+C you press to stop the program, hiding real bugs.
  • Keep the try block small, containing only the lines that might fail.
  • You can handle several types: except (ValueError, ZeroDivisionError):.
  • An optional finally: block runs whether or not an error happened, useful for cleanup.

Don't use try/except to hide bugs. If a NameError appears, fix the name; don't catch it.

Step 5 of 14Practice · Diagram

How try / except routes the program

text is "abc". Which branch runs?

Tap the shape that answers the question, then press Check.

How try / except routes the programHierarchy diagram: try: n = int(text), No error: continue with n, ValueError: except ValueError, Other error: crashes.try: n = int(text)No error: continuewith nValueError: exceptValueErrorOther error:crashes
try: n = int(text)
No error: continue with n
ValueError: except ValueError

Runs only if this exception type is raised.

Other error: crashes

Uncaught exceptions still produce a traceback.

Step 6 of 14Practice · Code challenge · Python

Complete safe_int(text, default=0) so it returns text converted to an integer, or default when the text can't be converted. Use try and except ValueError.

Real Python, running in a sandbox in your browser.
  • safe_int("42")
  • safe_int(" 7 ")
  • safe_int("ten")
  • safe_int("", -1)

Step 7 of 14Practice · What would you do?

What would you do?

A user types 0 when this program runs. What is printed?

try:
    n = int(input("Divide 100 by: "))
    print(100 / n)
except ValueError:
    print("Not a number")
print("Done")

Step 8 of 14Learn

Reading and writing files

Programs become truly useful when they work with files: reading data, writing reports, saving results. The safe way to open a file is with a with statement:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

with opens the file, gives it the name f, and closes it automatically when the block ends, even if an error happens inside. Forgetting to close files can lose data, so always use with.

The second argument is the mode:

ModeMeaning
"r" (default)read; FileNotFoundError if missing
"w"write; creates the file, or erases an existing one first
"a"append; adds to the end, keeping existing content

Mode "w" is the dangerous one: opening an existing report with "w" wipes it instantly. Use "a" to add to a log.

Useful details: f.read() returns the whole file as one string, and looping over f gives one line at a time, which works even for huge files. Each line ends with \n, so use line.strip() before comparing or converting. write() doesn't add newlines for you. Specifying encoding="utf-8" avoids garbled accented characters across systems. For spreadsheets, Python's csv module reads and writes comma-separated files properly.

Step 9 of 14Practice · Choose one

A file called sales.txt already contains 500 lines. What happens after running with open("sales.txt", "w") as f: f.write("total\n")?

Step 10 of 14Learn

Modules: standing on others' shoulders

Python comes with a huge standard library: modules for math, random numbers, dates, files, web requests, data formats and much more. To use one, import it:

import math
print(math.sqrt(81))        # 9.0
print(math.ceil(7.2))       # 8  (round up)
print(math.floor(7.8))      # 7  (round down)
print(math.pi)              # 3.141592653589793

import random
print(random.randint(1, 6))           # a dice roll, 1 to 6 inclusive
print(random.choice(["red", "blue"])) # a random item

from datetime import date
print(date.today())                   # e.g. 2026-11-24

import math makes the module available, and you use its contents with a dot: math.sqrt. from datetime import date imports one name directly, so you can write date without a prefix. Note that random.randint(1, 6) includes both ends, unlike range.

Beyond the standard library, hundreds of thousands of third-party packages are available from the Python Package Index. You install them with pip in a terminal, for example pip install requests, then import them like any module. Popular ones include pandas for data analysis, requests for web APIs and matplotlib for charts.

Two practical warnings. Never name your own file after a module you import: a script called random.py will import itself instead of the real module and fail mysteriously. And any .py file you write is a module too: import helpers loads functions from helpers.py in the same folder.

Step 11 of 14Flashcards

Handy standard-library modules

Tap a card to flip it.

Step 12 of 14Practice · Select all that apply

Which statements about modules and imports are true? Select all that apply.

Select all that apply.

Step 13 of 14Note

Step 14 of 14Practice · Work it out

What is math.ceil(7.2) + math.floor(7.2)?