From a sales sheet to a report you can check
Turn a CSV into a checked sales report with Python
In about 20 minutes, group six synthetic sales by product, verify a total of £111.80 and create a new CSV that opens in Excel. No account or payment card required.
If you use Excel and want to start automating reports, try this small task before deciding whether the full course suits you.
About 20 minutes · No account, card or Python installation required. Follow the instructions and complete two lines with help. You can read the sample on a phone; a computer is recommended for programming.
- 3guided lessons
- 5practical checks
- 1sales report
- £0free sample

What you will complete
Read six sales, group their amounts by product and check that the total agrees, while preserving the source.
The CSV opens in Excel. This sample creates a .csv summary rather than an .xlsx workbook and introduces a method you can extend later.
Finish with evidence
- The summary contains Keyboard £49.80, Mouse £37.50 and Notebook £24.50, sorted by product.
- The summary totals exactly £111.80 and invalid inputs are detected by tests.
- The code preserves the input rows and creates new CSV output without overwriting a file.
This is one guided example, not mastery of Python or completion of the full course.
Three lessons to do the work
Read the example, complete the operation and compare the output. Open each step whenever you need it.
01Understand the input and define the output
Your task is to repeat a small report with explicit rules. The file contains six sales and three columns. Each row is one sale: product names the item, units is the quantity and price is the unit price in pounds. The data is fictional and contains no customer details.
1. Read the CSV, remembering that its values are text
This CSV uses a semicolon separator. csv.DictReader turns each row into a dictionary and uses the first row as column names. After reading, '2' and '4.90' are still strings. Validate and convert them before multiplying; joining text would give the wrong result.
import csv, io
sales = list(csv.DictReader(io.StringIO(SALES_CSV), delimiter=';'))
print(sales[0])
# {'product': 'Notebook', 'units': '2', 'price': '4.90'} 2. Define the expected result first
We want one row per product, sorted by name, and its total sales amount. Notebook appears twice: 2 × £4.90 + 3 × £4.90 = £24.50. Mouse totals £37.50 and Keyboard £49.80. Together they must total £111.80. These are calculated reference values, not evidence that your code has already passed.
product;total_gbp
Keyboard;49.80
Mouse;37.50
Notebook;24.50 3. Preserve the original
The exercise creates a new dictionary for the summary and a new CSV string for the output. It does not modify the input rows or overwrite a source file. If an input is wrong, you can investigate and repeat the report while keeping the original evidence.
Check it yourself
Calculate Notebook by hand before continuing: £24.50. How many rows will the summary contain? Three, even though the input contains six sales.
02Validate the amounts and complete the grouping
A useful automation should not silently accept ambiguous data. This exercise validates each row before adding it and raises a clear error when the product, units or price breaks a rule. That validation is provided, so you can focus on completing the grouping.
1. Use an explicit rounding rule
Decimal represents decimal amounts from text. Use Decimal('4.90'), rather than Decimal(4.90), which starts from a binary float. This sample multiplies price by units, rounds each line to two decimal places with ROUND_HALF_UP, then adds the rounded lines. Under this rule, £1.005 becomes £1.01. A real project needs its own documented rounding policy.
from decimal import Decimal, ROUND_HALF_UP
amount = (Decimal('4.90') * 2).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(amount) # 9.80 2. Keep the running total in a dictionary
summary starts empty. For each row, validate_row returns a cleaned product name and the line amount. get(product, Decimal('0.00')) reads the existing total, using zero for a new product. Add the current amount and store the new total under the same product name. Keep the empty dictionary outside the loop.
previous = summary.get(product, Decimal('0.00'))
summary[product] = previous + amount 3. Complete your two lines
Find COMPLETE_GROUPING near the beginning of summarise_sales in the editor. Replace pass with the two lines above, keeping both indented inside the for loop. The rest of the programme is provided. Run and validate: the console shows the report followed by the test result. Use a hint or the complete solution if needed, then explain why get needs a starting value.
Check it yourself
Why is summary[product] = amount insufficient? A later sale of the same product would overwrite its earlier amount instead of adding to it.
03Check, export and repeat reliably
A neat-looking table does not prove that its amounts are correct. We check a known example, the total, repeated products, awkward amounts and preservation of the input. Then we create an Excel-compatible output.
1. Use tests that can genuinely fail
The lab checks valid examples and invalid inputs. An empty list should return {}; None is not a list and must be rejected. Units of 0 or 1.5 break this example's rule. NaN and infinity are not valid prices. Comparing a deep copy before and after the call detects accidental changes to input rows.
assert summary['Notebook'] == Decimal('24.50')
assert sum(summary.values(), Decimal('0.00')) == Decimal('111.80')
assert summarise_sales([]) == {} 2. Create a new CSV for Excel
create_summary_csv writes a semicolon-separated CSV string with decimal points. Copy the console output into a NEW file named sales_summary.csv. In Excel, choose UTF-8 and a semicolon separator in the import dialogue if needed. The starter and solution downloads contain the same code and dataset as the lab. They need Python 3.10 or later and do not install packages.
output_text = create_summary_csv(summary)
print(output_text)
# The original SALES_CSV remains unchanged. 3. Know the limits of this sample
This is one guided task using synthetic data. It does not process real customer files, create .xlsx workbooks or schedule unattended runs. Input limits and rejection of product names beginning with =, +, - or @ reduce formula-export risks from that field; they do not make this a production system.
Check it yourself
Finish with two pieces of evidence: the total £111.80 and the message confirming that the automated checks passed. Then answer the five questions below.
Complete it in the Python lab
Find COMPLETE_GROUPING inside summarise_sales. Replace pass with the two lines from lesson two. The rest of the programme is provided.
Your code runs in your browser and is not sent to KINTAVOR. The editor remembers your work in this browser. Use only the fictional example: do not paste personal data, passwords or API keys.
Ready. Complete the grouping and select “Run and validate”.
Console and checks
The first run downloads the Python engine and may take a moment. If your browser cannot run it, download the exercise and use Python 3.10 or later on your computer.
I need a hint
- Hint 1: each line amount is already validated and rounded. Your task is to add it to the total for that product.
- Hint 2: read the previous total with summary.get(product, Decimal('0.00')). Do not put summary = {} inside the loop.
- Hint 3: store previous + amount in summary[product]. Give both lines the same indentation as the call to validate_row.
Show the complete solution
Try first, then compare the running total, validation and final result. Copy the full solution into the editor and run it to check it yourself.
"""KINTAVOR educational sample. Synthetic data; standard library only."""
import csv
import io
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
def summarise_sales(rows):
"""Group amounts by product, sorted, without changing the original rows."""
if not isinstance(rows, list):
raise TypeError("rows must be a list of dictionaries.")
if len(rows) > 10000:
raise ValueError("This sample accepts at most 10000 rows.")
summary = {}
for row_number, row in enumerate(rows, start=1):
product, amount = validate_row(row, row_number)
# COMPLETE_GROUPING: solution
previous = summary.get(product, Decimal('0.00'))
summary[product] = previous + amount
return dict(sorted(summary.items()))
SALES_CSV = """product;units;price
Notebook;2;4.90
Keyboard;1;24.90
Notebook;3;4.90
Mouse;2;12.50
Keyboard;1;24.90
Mouse;1;12.50
"""
def read_sales(text):
"""Read a semicolon-separated CSV; values remain text."""
if not isinstance(text, str):
raise TypeError("The CSV must be text.")
reader = csv.DictReader(io.StringIO(text), delimiter=";")
if reader.fieldnames != ["product", "units", "price"]:
raise ValueError("Expected header: product;units;price")
return list(reader)
def validate_row(row, row_number):
"""Return the product and line amount; reject ambiguous input."""
if not isinstance(row, dict) or set(row) != {"product", "units", "price"}:
raise ValueError(f"Row {row_number}: product, units and price are required.")
product = row["product"]
if not isinstance(product, str) or not product.strip():
raise ValueError(f"Row {row_number}: the product is missing.")
product = product.strip()
if len(product) > 80 or product.startswith(("=", "+", "-", "@")):
raise ValueError(f"Row {row_number}: this product name is not allowed in this CSV.")
units = row["units"]
if isinstance(units, bool) or not isinstance(units, (int, str)):
raise ValueError(f"Row {row_number}: units must be a positive integer.")
units_text = str(units).strip()
if len(units_text) > 6 or not units_text.isascii() or not units_text.isdecimal():
raise ValueError(f"Row {row_number}: units must be a positive integer.")
quantity = int(units_text)
if not 1 <= quantity <= 100000:
raise ValueError(f"Row {row_number}: units must be between 1 and 100000.")
value = row["price"]
if isinstance(value, bool) or not isinstance(value, (str, int, float, Decimal)):
raise ValueError(f"Row {row_number}: the price is invalid.")
price_text = str(value).strip()
if not price_text or len(price_text) > 64:
raise ValueError(f"Row {row_number}: the price is invalid.")
if isinstance(value, str):
parts = price_text.replace(",", ".").split(".")
if len(parts) > 2 or any(not p.isascii() or not p.isdecimal() for p in parts):
raise ValueError(f"Row {row_number}: use a price without thousands separators.")
try:
price = Decimal(price_text.replace(",", "."))
except (InvalidOperation, ValueError):
raise ValueError(f"Row {row_number}: the price is not numeric.") from None
if not price.is_finite() or not Decimal("0") <= price <= Decimal("1000000"):
raise ValueError(f"Row {row_number}: the price must be between 0 and 1000000.")
# Explicit rule: round EACH LINE to pennies before grouping.
amount = (price * quantity).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return product, amount
def create_summary_csv(summary):
"""Create NEW CSV output with decimal points, preserving the original."""
output = io.StringIO(newline="")
writer = csv.writer(output, delimiter=";", lineterminator="\n")
writer.writerow(["product", "total_gbp"])
for product, amount in summary.items():
writer.writerow([product, format(amount, ".2f")])
return output.getvalue()
sales = read_sales(SALES_CSV)
summary = summarise_sales(sales)
print(create_summary_csv(summary))
print("Total:", format(sum(summary.values(), Decimal("0.00")), ".2f"), "GBP")
Download solution and testsCompare your output with this result
Expected output for the six fictional sales. Compare it with your console; this reference table does not change when you edit the code.
This is a reference table, not a chart that updates from your code. The lab console shows what your programme actually calculated.
| Product | Amount |
|---|---|
| Keyboard | £49.80 |
| Mouse | £37.50 |
| Notebook | £24.50 |
| Total | £111.80 |
Synthetic amounts in GBP, not student earnings or results.
Five practical checks
Make small changes and observe the effect. Understanding an error is part of the exercise.
- 01
Inspect the CSV input
Run print(sales[0]) in a copy of the editor. Explain why units and price arrive as text and which separator DictReader uses.
- 02
Complete the running total
Complete the two marked lines and run the checks. Notebook must combine two sales into £24.50, rather than keeping only £9.80 or £14.70.
- 03
Check a rounding edge case
Try two rows for one product, with one unit at '0.005' each. The result should be £0.02 because each line is rounded first. Rounding only the combined amount would give £0.01.
- 04
Trigger and understand an input error
In a copy of the sales, change units to '1.5'. You should see ValueError rather than a silently altered report. Reset afterwards to restore the clean example.
- 05
Explain the result and preserve the source
Write down the three summary rows and the £111.80 total. Explain why the summary is new and how you would check that the original rows stayed unchanged.
Check what you have learnt
Five different questions about this exercise, with feedback on every answer. This is not a certification exam or a general placement assessment.
Want to apply this method to more tasks?
This sample teaches one small, verifiable task. The full self-paced course extends the work to automation, Excel, data quality, SQL, integrations and portfolio projects. Review its programme, format, requirements, terms and current price before deciding. This short check reviews the sample; it does not certify a professional level or recommend skipping course modules.
Private, self-paced training without live classes. A private, unofficial certificate. Employment and income are not guaranteed. Seller: MYSERVEAI TECHNOLOGIES SL · Tax ID B23836711. KINTAVOR is the trading name.