Lesson 4 of 38 · Written learning
Functions, files, and errors
Organize small programs and read common text-data formats safely.
A function can accept data, return a result, and leave unrelated state unchanged. Modules group related functions so another file can import them. Classes are useful when data and behavior belong together, but a small script does not need a class just because Python allows one.
Read data deliberately
Text files are lines of characters; CSV represents tabular rows; JSON represents nested objects, arrays, strings, numbers, and Booleans. Check the encoding, required fields, and file path. An exception is a signal that an operation failed. Catch a specific exception when you can handle it; do not turn every error into an empty result, because that can make corrupted output look successful.
- Write a function that accepts a text string and returns a cleaned string.
- Keep file input and output at the edge of the program so the transformation is easy to test.
- Validate required JSON keys and report which field is missing.
- Include a short example of expected input and output in the README.
Return to the Python and software foundations stage · Suggested timing is flexible; move at your own pace.