Exercises
Practice the chapter's boundary, conversion, file, path, import, collection, and program-organization decisions in twelve cumulative tasks.
Read the Boundary
Q1. Preserve the newline evidence
A UTF-8 file contains two lines. Its complete text is
"north,18.5\nwest,24.0\n". Which value does file.read() return?
Select one choice, then check.
HintKeep reading separate from parsing
Ask what read() does before any call to split, strip, or float.
SolutionReturn the complete decoded string
file.read() returns "north,18.5\nwest,24.0\n". Parsing and numerical
conversion are later operations.
Q2. Distinguish a path from its contents
What does Path("data") / "measurements.txt" produce before the program opens
anything?
Select one choice, then check.
HintLook for an input operation
The expression contains Path and /, but no open, read, or write.
SolutionName the location only
The expression produces a path value. The program must perform a separate file operation to learn whether the path exists or what it contains.
Keep Text and Bytes Distinct
Q3. Compare characters and UTF-8 bytes
The label "café" has four characters. Its UTF-8 encoding contains the byte
integers [99, 97, 102, 195, 169]. Which statement is correct?
Select one choice, then check.
HintCount each sequence
str contains characters. bytes contains byte values.
SolutionKeep the two lengths separate
len("café") is 4, while the given encoded sequence has five byte values.
The non-ASCII final character uses more than one UTF-8 byte.
Q4. Verify a strict binary round trip
Complete the program so it encodes the label with UTF-8, writes exact bytes, reads them back in binary mode, and decodes them to the original text.
Editable Python
Ready to run.
HintMatch the mode to the value
encode produces bytes for wb. Reading with rb returns bytes for
decode.
SolutionWrite and restore the same bytes
Parse and Report One Invalid Row
Q5. Preserve line identity while parsing
Complete the parser. It must report the invalid east reading with line number 2, keep the five valid labelled readings, and print their mean.
Editable Python
Ready to run.
HintKeep the try block narrow
Preserve line_number and label outside the conversion. Put only
reading = float(text) under try.
SolutionReport and skip at the input boundary
Write for the Result You Mean
Q6. Choose replacement or append
Each run produces one complete current summary. A later run should replace the earlier summary. A separate audit log should retain one new line per run. Which mode pairing fits those meanings?
Select one choice, then check.
HintUse meaning, not habit
The summary should contain one report after every run. The log should keep earlier entries.
SolutionReplace the summary and extend the log
Use w for the generated summary and a for the audit log. The choice
follows the result's contract.
Q7. Write and verify exact report text
Complete the write and read-back. A seeded older report must be replaced, and the saved text must match the intended report exactly.
Editable Python
Ready to run.
HintVerify after closing the writer
Use one with block for writing and a later with block for reading.
SolutionRead back the completed write
Diagnose Locations and Imports
Q8. Use path evidence before guessing
The runner expects data/measurements.txt, but input_path.is_file() is false.
The output folder also does not exist. Which next step preserves the evidence?
Select one choice, then check.
HintSeparate ownership
The program creates its generated report. Another source was expected to supply the measurements.
SolutionInspect input and create output deliberately
Use Path.cwd(), input_path.resolve(), and input_path.is_file() to locate
the mismatch. Do not invent input. Create output_path.parent only before
writing generated output.
Q9. Keep imported names traceable
Which description of these imports is correct?
Select one choice, then check.
HintName the source of each import
Python ships collections; the project owns measurement_tools.py; NumPy is a
separately installed library used later in the subject.
SolutionDistinguish the three origins
Counter comes from the standard library, parse_measurements from a local module,
and np is the conventional local name for the third-party NumPy module.
Reuse Understood Collection Work
Q10. Verify Counter and defaultdict against loops
Complete the standard-library count and grouping. Both results must equal the supplied manual dictionaries.
Editable Python
Ready to run.
HintUse one tool for each established role
Counter consumes the full class sequence. A defaultdict with the list
factory creates one group for a new sensor label.
SolutionKeep the equivalence visible
Connect the Complete Program
Q11. Assign one owner to each role
Which layout keeps supplied data, reusable functions, workflow, and generated output distinct without adding an unnecessary layer?
Select one choice, then check.
HintGrow only for a real role
Four different responsibilities justify four clear destinations. Empty abstraction layers do not help the reader inspect the workflow.
SolutionUse the compact four-role layout
The first layout separates supplied input, reusable transformations, the runner, and generated output. It adds no file without a job.
Q12. Repair and rerun the complete workflow
The browser setup supplies data/measurements.txt, but the runner requests the
wrong filename and appends its current report. Repair both defects. The same
workflow must run twice, replace rather than duplicate the report, and verify
the exact read-back on both runs.
Editable Python
Ready to run.
HintPreserve supplied input and one current report
Change the requested filename to measurements.txt. Open the generated
summary with w inside each run so the second result replaces the first.