Basic Python (AI-powered) · Lesson 3 of 3
Python Functions, Files, and Reusable Analysis
Write small functions and load data from files with explicit paths and encodings.
Lesson
1. Introduction
A notebook becomes easier to rerun when repeated logic lives in functions and input/output boundaries are explicit. Functions also make calculations testable without needing to repeat an entire manual notebook workflow.
2. Understand the concept
A function receives arguments and returns a result. A CSV reader maps columns to values; JSON maps structured objects to Python dictionaries and lists. File paths depend on the process working directory, and text files should use an explicit encoding such as UTF-8.
3. Syntax and interpretation
from pathlib import Path
import csv
def read_rows(path: Path) -> list[dict[str, str]]:
with path.open(newline='', encoding='utf-8') as file:
return list(csv.DictReader(file))The with statement closes the file even if reading fails. DictReader uses the header row as field names and keeps CSV values as strings until converted.
4. Apply it to an analysis
Write small functions and load data from files with explicit paths and encodings. Start with a small, known example and state what each row or value represents. After the transformation, check row counts, types, keys, and units against the original data. If an assumption fails, stop and investigate instead of presenting the output as a valid result.
5. Common mistakes
- Using a mutable list as a default function argument.
- Assuming relative paths are relative to the script rather than the current working directory.
6. Practice task
Write a function that accepts a list of values and returns the largest value, or None for an empty list.
7. One possible solution
def largest(values): return max(values) if values else None. Add type hints when the expected value type is known.8. Summary and next step
Write small functions and load data from files with explicit paths and encodings. Continue to the next course section and apply this foundation to a different analytics tool or workflow.
Visual guide
Working through Python Functions, Files, and Reusable Analysis
-
Step 01
Define
State the question, data grain, and expected output.
-
Step 02
Apply
Use the method and check its assumptions on a small example.
-
Step 03
Verify
Reconcile the result and communicate limitations.
Code examples
def mean(values: list[float]) -> float | None:
return sum(values) / len(values) if values else None
print(mean([2, 4, 6]))
4.0
import json
from pathlib import Path
payload = json.loads(Path('settings.json').read_text(encoding='utf-8'))
print(payload.get('region', 'Unknown'))
The region value, or Unknown when that key is absent.
Key points
- Write small functions and load data from files with explicit paths and encodings.
- Check the result against the stated data definition and a representative example.
- Record assumptions and report data-quality limitations rather than hiding them.
Check your understanding
Practice
Your learning progress