Python Intermediate Lesson 3: Errors, try/except and Logging

Python Intermediate Lesson 3: Errors, try/except and Logging 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 3 of 10

Advertisement
In this article
  1. logging instead of print
  2. Common mistakes
  3. Practice

Real files contain blanks, typos and impossible dates. The sales file in this course has two: a missing quantity and the date 31-06-2026 (June has 30 days). A good script skips such rows, says exactly which ones, and finishes the job.

good, bad = [], []
for line_no, r in enumerate(csv.DictReader(open("sales.csv")), start=2):
    try:
        r["qty"] = int(r["qty"])
        r["date"] = dt.date.fromisoformat(r["date"])
        good.append(r)
    except ValueError as e:
        bad.append(line_no)
        log.warning("line %d skipped (%s): %s", line_no, r["invoice"], e)

Catch the specific exception you expect (ValueError, KeyError, FileNotFoundError). A bare except: also hides your own bugs.

logging instead of print

import logging
logging.basicConfig(filename="report.log", level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("sales")
log.info("loaded %d rows", len(good))

Levels (DEBUG, INFO, WARNING, ERROR) let you see details while testing and only problems in production. A log file is what tells you, next Monday, why the 6 a.m. scheduled run produced a short report.

πŸ’‘ finally: runs whether or not an error happened: close connections, delete temp files. With files, with open(...) as f: does this for you.

Common mistakes

  • Silently skipping rows with except: pass. Always count and log what you skipped.
  • try around the whole script: keep try blocks small, around the line that can fail.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 3 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 1 KB
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 263 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *