Read data and catch mistakes
Load CSV data, handle expected failures, and check important results. This module has 3 lessons and takes about 1h. Each lesson has a practice exercise that runs real Python in your browser and a short quiz.
Start module 05 in the Learning LabRead and write CSV data
Turn a tiny CSV table into a daily energy total.
import loads a module: a collection of reusable Python tools. csv reads and writes CSV tables. io.StringIO makes a text stream in memory, so this example needs no uploaded file.
csv.DictReader uses the first row as dictionary keys. Its values are text, so convert the kwh field with float before adding it. DictWriter writes dictionaries using a chosen column order.
On your computer, the same pattern works inside with open("readings.csv", newline="", encoding="utf-8") as source:. with closes the file when the block ends. The CSV below is synthetic.
See it in action
import csv
import io
# Synthetic daily solar readings
csv_text = "day,kwh\nMon,8.5\nTue,9.0\nWed,7.5\n"
with io.StringIO(csv_text) as source:
total_kwh = 0
for row in csv.DictReader(source):
total_kwh += float(row["kwh"])
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["period", "kwh"])
writer.writeheader()
writer.writerow({"period": "3 days", "kwh": total_kwh})
print(output.getvalue())
Parse tables with a CSV tool, convert types, and close file resources.
Handle a bad value without hiding it
Keep valid sensor values and count rejected entries.
Some inputs fail during conversion. float("offline") raises ValueError. A try block attempts work, and except ValueError handles that specific failure.
Keep the try block small and catch only errors you expect. Replacing every bad reading with zero would create a false measurement. Count rejected entries instead.
In this synthetic temperature import, a valid zero is still a real value. The text "offline" is missing information. We keep those two cases separate.
See it in action
# Synthetic sensor export
raw_readings = ["24.5", "offline", "0", "25.0"]
valid_readings = []
rejected_count = 0
for raw in raw_readings:
try:
value = float(raw)
except ValueError:
rejected_count += 1
else:
valid_readings.append(value)
print("Valid:", valid_readings)
print("Rejected:", rejected_count)
Recover from expected errors while keeping rejected data visible.
Check results with small tests
Test a supply calculator with ordinary, zero, and boundary cases.
A test compares the result you get with the result you expect. assert condition stops with AssertionError if the condition is false. A useful message explains the failure.
Tests should cover normal inputs and edges. For packing items into boxes, test zero items, a partly filled box, and an exact multiple. // performs floor division, and % gives the remainder.
This synthetic supply exercise has no clinical rules. Assertions are useful for learning checks and tests. Use explicit validation for required runtime checks because Python can disable assert in optimized mode.
See it in action
def boxes_needed(items, capacity):
# Inputs: items >= 0 and capacity > 0, both whole numbers.
full_boxes = items // capacity
if items % capacity != 0:
return full_boxes + 1
return full_boxes
assert boxes_needed(0, 20) == 0
assert boxes_needed(20, 20) == 1
assert boxes_needed(21, 20) == 2
print("Three checks passed")
Test the edges where your rule changes, not only one easy example.
Free, open and run by a nonprofit.
This page is part of Python to AI, a free course of 20 modules and 60 lessons in the engineering.fit( ) Learning Lab. The Learning Lab is built and run by engineering.fit( ), a nonprofit founded by Abdullateef Opeyemi Bakare that helps African engineering students gain research experience. You do not need an account or pay a fee to learn.