Editor

Fix the CSV Sum Bug

Intermediate · Fix the bug · from Python CSV: Read, Write, and Process CSV Files

From the lesson: Python CSV: Read, Write, and Process CSV Files

Think about a spreadsheet with rows and columns - names in one column, ages in another, scores in a third. A CSV file (Comma-Separated Values) is just a plain text version of that spreadsheet, where commas separate each column.

Read the lesson

This code tries to calculate the total price from CSV data, but it produces a wrong result. Fix the bug.

Expected output:

Total: 120
import csv
import io
data = 'item,price\nBook,20\nPen,5\nBag,95'
f = io.StringIO(data)
reader = csv.DictReader(f)
total = 0
for row in reader:
total += row['price']
print(f'Total: {total}')

More CSV exercises

All Python exercises · 50 practice problems · File I/O & Data Formats quiz