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.00Design
| Function | Purpose |
|---|---|
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.
- Import
csv. - Define a function named
compute_totalthat takesrow. Inside, returnint(row["quantity"]) * float(row["price"]). - Define a function named
generate_reportthat takesinput_fileandoutput_file. Inside, openinput_filein read mode, create acsv.DictReadernamedreader, and assignlist(reader)torows. - Still inside
generate_report, createresults = []andgrand_total = 0.0. Write aforloop overrows. Inside, createtotal = compute_total(row). Addtotaltogrand_total. Append{"product": row["product"], "total": f"{total:.2f}"}toresults. - Still inside
generate_report, openoutput_filein write mode withnewline="". Create acsv.DictWriternamedwriterwithfieldnames=["product", "total"]. Callwriter.writeheader(). Callwriter.writerows(results). Returngrand_total. - Create
total = generate_report("sales.csv", "report.csv"). - Call
print("Report written to report.csv."). - Call
print(f"Grand total: ${total:.2f}").
# sales.csv contains: # product,quantity,price # Laptop,2,500.00 # Mouse,5,20.00 # Keyboard,3,60.00 # Step 1: Import csv # Step 2: Define compute_total(row) # Step 3: Define generate_report(input_file, output_file) — read input_file rows # Step 4: Compute totals and build results list with grand_total # Step 5: Write results to output_file and return grand_total # Step 6: Call generate_report and store the result in total # Step 7: Print "Report written to report.csv." # Step 8: Print the grand total formatted as currency
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding