Mini Project: Sales Report
Exit

Mini Project: Sales Report

Read a sales CSV, compute totals, and write a summary report

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

What you will build

A sales analyzer that reads product data, computes the revenue for each product, writes a summary CSV, and prints the grand total.

Example output

Report written to report.csv.
Grand total: $1280.00

Design

FunctionPurpose
compute_total(row)Return quantity × price for one row
generate_report(input_file, output_file)Read sales, write totals, return grand total

Instructions

Build the sales report generator.

  1. Import csv.
  2. Define a function named compute_total that takes row. Inside, return int(row["quantity"]) * float(row["price"]).
  3. Define a function named generate_report that takes input_file and output_file. Inside, open input_file in read mode, create a csv.DictReader named reader, and assign list(reader) to rows.
  4. Still inside generate_report, create results = [] and grand_total = 0.0. Write a for loop over rows. Inside, create total = compute_total(row). Add total to grand_total. Append {"product": row["product"], "total": f"{total:.2f}"} to results.
  5. Still inside generate_report, open output_file in write mode with newline="". Create a csv.DictWriter named writer with fieldnames=["product", "total"]. Call writer.writeheader(). Call writer.writerows(results). Return grand_total.
  6. Create total = generate_report("sales.csv", "report.csv").
  7. Call print("Report written to report.csv.").
  8. Call print(f"Grand total: ${total:.2f}").