KajoData / python en
Custom Python functions: from a sales list to CSV files
I start with a function that totals product units, then add CSV reading and directory selection. Each stage has its own inputs, output and stated limits.

You have three sales records and want to total the units of one product. Then a second file arrives. Later, there is a whole directory and a product name someone wants to change without rewriting the program. This is a useful point to introduce custom functions.
I start with a small calculation and clear boundaries. One function totals units from prepared records. Another turns a file into those records. A third selects files and combines their results. A broken header then remains a different problem from incorrectly adding quantities.
The examples are synthetic and use the Python 3.14 standard library. Expected results follow from the documentation and the visible input. You do not need pandas to understand this division. If lists and dictionaries are still unfamiliar, start with the Python introduction.
Write the function’s contract first
I want the number of units sold for a selected product. The input is a list of dictionaries, each containing a product name and an integer quantity. The records have already been prepared. The counting function does not open files, ask the user a question or save a report.
That boundary is deliberate. I can reuse the same calculation with records from a file, a small notebook example or another part of a program. The product name is an argument, rather than a fixed string hidden inside the function.
I use exact, case-sensitive name matching. Under this contract, Apple and apple are different values. I do not automatically remove accents or merge similar names. For a real report I would prefer a stable product code, but a simple name keeps this lesson focused on function behaviour.
An empty list or a product without matching records should produce zero. That does not establish that an import succeeded. A later stage will distinguish an absent input directory from valid data containing no sales of the selected product. The counting function sees only the records it receives.
Define the function, arguments and result
The function documentation explains definitions using def and results passed through return. Here is a complete small example:
sales_data = [
{"product": "Apple", "quantity": 2},
{"product": "Banana", "quantity": 1},
{"product": "Apple", "quantity": 3},
]
def total_units(data, product):
total = 0
for row in data:
if row["product"] == product:
total += row["quantity"]
return total
apple_units = total_units(sales_data, "Apple")
print(apple_units)
The expected result is 5: the first and third records contribute two and three units. Banana is excluded. Calling the function with Pear gives zero because no record satisfies the condition. The arithmetic is small enough to follow directly without another tool.
Indentation matters. A return placed inside the loop would finish the call during the first iteration, before examining the remaining data. Here it sits after the loop, while still inside the function. The initial zero is created for every call, so later calls do not accumulate earlier totals.
Print displays a value; return makes it available to the caller
If a function only prints a total, the screen may show the right number without the caller receiving that number as a value. A function that does not explicitly return a value returns None. Assigning its call to a variable does not turn the printed text into a numeric result.
I therefore return the total from the calculation and leave display outside. I can later compare it with a target, pass it to a chart or write it to a report. A presentation change does not require removing print statements from several parts of the calculation.
A parameter is also a local name used inside the call. The original list can have another name in the calling code. What matters is the object passed in and the structure promised by the contract. Accidentally referring to a global list instead of the parameter would make reuse harder.
The calculation does not modify the records either. It reads them and adds quantities to its own total. If another function were intended to clean input records in place, I would state that explicitly. Callers should know whether their original list still means the same thing after an operation.
CSV has rules a simple split does not cover
Now the records live in sales_january.csv:
date,product,quantity
2026-01-01,Apple,2
2026-01-02,Banana,1
2026-01-03,Apple,3
This synthetic input uses commas, UTF-8 and exactly three columns in the shown order. The header names are part of the contract. A file with different names or a semicolon separator needs another configuration or an explicit format change before reading.
Splitting a line at every comma fails for a product field such as "Apple, green". The comma belongs inside one field. The csv module interprets such rules, while DictReader associates values with names from the first row. Fields remain text until I explicitly convert them.
I open the file with newline="", as the module documentation specifies. The utf-8-sig encoding accepts UTF-8 with or without a BOM. It does not automatically identify every legacy encoding. A promise to “read CSV” should not conceal guesses about the input format.
Read one file and report explicit input errors
The following function checks the header, field count, product name and quantity. This exercise accepts nonnegative integer quantities. Returns and fractional units sit outside the stated definition. The date remains text; the function does not yet establish whether it is a valid calendar date.
import csv
from pathlib import Path
def read_sales(path):
records = []
with open(path, encoding="utf-8-sig", newline="") as file:
reader = csv.DictReader(file, strict=True)
if reader.fieldnames != ["date", "product", "quantity"]:
raise ValueError(f"{path}: expected date,product,quantity header")
for row in reader:
location = f"{path}, line {reader.line_num}"
if None in row or any(value is None for value in row.values()):
raise ValueError(f"{location}: wrong number of fields")
product = row["product"].strip()
if not product:
raise ValueError(f"{location}: empty product")
try:
quantity = int(row["quantity"])
except ValueError as error:
raise ValueError(f"{location}: invalid quantity") from error
if quantity < 0:
raise ValueError(f"{location}: negative quantity")
records.append({
"date": row["date"],
"product": product,
"quantity": quantity,
})
return records
This is a separate definition using the imports shown above it. The returned list has the structure expected by the earlier function. Calling total_units(read_sales("sales_january.csv"), "Apple") should therefore give five units from the stated input.
The field-count check uses documented DictReader behaviour: extra fields go under a None key by default, while missing fields receive None values. An empty string is different from an absent field. I require a nonempty product name, but this example does not yet reject an empty date.
If the quantity contains three, int conversion fails. The text 3.0 also fails the integer-text conversion used here. A negative integer converts successfully but fails the range rule. The code separates the ability to parse a number from accepting its meaning in a particular report.
Stopping the import is a deliberate choice
I do not wrap the entire function in a broad exception handler that returns an empty list for every problem. The report could then show zero even though part of the sales input was never read. Zero looks harmless until someone makes a decision based on it.
In this version, an invalid record stops reading and no partial result is returned as a complete dataset. Exceptions communicate the problem to the caller. File, encoding and CSV syntax errors can also occur alongside our own validation errors. This example does not conceal them.
The reader.line_num value counts physical lines consumed by the parser. A field containing a newline can make the line number differ from the record number. The message therefore identifies a line, without promising a transaction number the program does not know.
Another design could separate accepted records from rejected records. Its result should expose both groups and a rejection count. Quietly skipping errors while still calling the total complete sales would misrepresent the output. The appropriate policy depends on the process rather than which message causes less inconvenience.

Compose the functions for a directory
For this exercise, a second file, sales_february.csv, contains one record:
date,product,quantity
2026-02-01,Apple,4
I put both files in the data directory. The expected Apple total is nine units: five from January and four from February. The result follows from visible input rather than an unexplained number attached to a function call.
def total_units_from_directory(directory, product):
folder = Path(directory)
if not folder.is_dir():
raise FileNotFoundError(f"{directory}: directory unavailable")
paths = sorted(path for path in folder.glob("*.csv") if path.is_file())
if not paths:
raise FileNotFoundError(f"{directory}: no matching CSV files")
total = 0
for path in paths:
total += total_units(read_sales(path), product)
return total
print(total_units_from_directory("data", "Apple"))
This function uses both earlier definitions and the Path import. Path.glob selects matching paths. The pattern covers the current directory without recursively searching subdirectories. Filtering with is_file excludes a directory whose name happens to end like a file.
Sorting establishes a traversal order. Integer addition does not require that order, but reading and explaining failures becomes more predictable. Filename case matching can depend on the platform. I do not promise that an uppercase extension will always match this pattern.
Empty files and repeated exports need separate decisions
No matching files produces an error in this function rather than zero. A file with the correct header and no records returns an empty list, contributing zero to the total. A completely empty file fails the header check. These are three different situations that I want to keep distinguishable.
The directory function also assumes the selected folder is an agreed and complete input. If someone leaves both a January export and its copy there, both may be counted. A file extension does not establish that its records are new. Sorting filenames does not remove repeated transactions either.
Before using this in a recurring report, I would establish the file inventory, export periods and event key. Our simplified records lack transaction identifiers, so they do not support reliable deduplication. Identical rows might represent two legitimate sales or the same sale exported twice.
I do not describe this as a universal import system. It holds one file at a time in memory as a list, does not guarantee a snapshot of the directory and does not record processing history. Larger data may call for streaming. A recurring process also needs to track what has already been accepted.
Annotations and docstrings should describe the actual contract
I can add expectations for the product and result: def total_units(data, product: str) -> int:. A reader then knows that I expect a text product name and return an integer unit count. This helps when calling the function elsewhere.
However, Python does not enforce ordinary type annotations at runtime. The annotation does not turn CSV text into a number or establish that a dictionary contains the required keys. Our reading stage still performs those duties. Adding a return annotation does not make the program automatically correct.
A useful docstring would state the output unit, input structure and missing-product behaviour. For the reader function, it would also state the file format, encoding and rejection conditions. “Reads data” communicates much less than the requirement for three columns and nonnegative quantities.
I also pay attention to defaults. If I later introduce an optional list, I avoid using a shared empty list to accumulate results across calls. Default argument values are created when the function is defined, which can surprise readers when a mutable object is involved. Explicit arguments keep this lesson straightforward.
Extend the solution along its existing boundaries
When a requirement changes, I identify the boundary it affects. A different separator changes reading. A different product name changes an argument. A report by product requires another aggregation. Writing a result to disk is another responsibility. Everything need not be attached to the same directory loop.
Suppose the reader now wants revenue. Our input contains quantities alone. Nine units cannot become nine monetary units by changing a column label. I need prices, discount definitions and accounting rules. No function design can supply information missing from the source.
Likewise, storing a date as text does not guarantee correct monthly grouping for arbitrary formats. Such an extension calls for explicit parsing and range checks. The current code demonstrates function composition without claiming to solve every sales-data quality problem.
I keep the input small enough to explain each change mentally. I know which two records produce five and which file adds four. That lets me trace the result from source to total. If I cannot explain the small case, adding more directories usually just hides the problem.
Give the result enough context to judge its completeness
Alongside the total, I would expose the input scope. Nine units from two agreed files means something different from nine units in one incomplete export. Useful next outputs include file count, accepted record count and the covered period. These help a reader assess whether the report is complete.
I would not infer the period solely from filenames. A file labelled February might contain a January correction or an accidental full-history export. I need an agreement about whether to trust the filename or inspect record dates. The current reader retains dates as text, so month validation would be an explicit extension.
Input stability matters as well. Someone adding or changing files during calculation can make the directory differ from the input described by the report. A prepared folder that remains unchanged is enough for this exercise. A recurring process needs an agreed handover of complete batches and a way to recognise readiness.
Finally, I decide who receives a failure. The operator needs enough detail to locate the file and line. The business reader needs to know that the report was not produced for the complete scope. Giving both people only an empty table hides the failed import between stages. Clear function boundaries should help communicate that outcome.
Exercise: identify which boundary should reject the input
Change the February quantity to four. Reading should report an invalid quantity. Then restore the numeric value and rename the quantity column to units. This time the problem should be detected before processing records, during header validation.
Next, use valid files and ask for Pear. Zero is consistent with the contract because that product has no records. Compare this with a directory containing no files. Explain why the same displayed zero should not conceal both situations. The exercise concerns the meaning of a report as much as Python syntax.
Finally, add another valid Apple record for one unit and predict the total before changing any calculation. Suggest how to expose the number of accepted files alongside the result. A next step is text reading and the limits of split or extending your own small import around a clearly stated contract.
I should be able to explain a function name in one sentence, including its output unit. If that description contains several independent promises, I consider separating responsibilities before adding more parameters.
Key takeaways
How does return differ from print?
return passes a result to the calling code and ends that function call. print displays information; displaying a number does not return it as the function's result.
Why not split every CSV line on a comma?
A quoted CSV field may contain a comma or even a newline. csv.DictReader interprets CSV rules and associates fields with the header.
Does an int annotation check the type at runtime?
No. Ordinary annotations document expectations and help tools. You still need explicit conversion of text into numbers and checks for required input rules.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
