03. Control flow — Mini-project
The server-room sensor writes one temperature per line to a log file. The file has gaps and junk lines. Before anyone uses the data for a dashboard or a model, the data team wants a quality report: which lines are broken, how the valid readings are spread, what each hour looked like and whether an alarm condition happened.
Write a script, sensor_quality.py, that reads the log and prints the report below. In module 01 you typed six values by hand. Now a loop does the work for every line of the file, and the same script works for tomorrow’s file.
The project uses most of module 03: for loops, range() with a step, enumerate(), zip(), if-elif-else, truthiness, continue, break, a loop else and match-case with sequence patterns and a guard. Stretch goal 4 adds a while loop.
Dataset
Section titled “Dataset”data/readings.txt has 43 lines, one temperature in °C per line. Three lines are broken: error (line 12), an empty line (line 24) and n/a (line 35). The 40 valid values run from 19.3 to 22.9 °C.
For this project, assume that the log starts at 00:00 and has one line every 10 minutes. So line 1 is 00:00, line 7 is 01:00 and line 43 is 07:00. Six lines make one hour.
| Setting | Value |
|---|---|
| Interval | 10 minutes per line |
| Bands | cool below 20.0 °C, normal 20.0–22.0 °C, warm above 22.0 °C |
| Alarm | the first reading below 19.5 °C |
| Jump | the largest change between two consecutive valid readings |
| Verdict | clean with 0 broken lines, usable with up to 10% broken lines, else reject |
Requirements
Section titled “Requirements”Your script must:
- Read the lines of
data/readings.txtwithPath(...).read_text(encoding="utf-8").splitlines(). - Classify every line as empty, invalid or valid, with its line number. Use
match text.split():with sequence patterns and a guard, andcontinueto skip broken lines. - Print one problem line per broken line, with its line number and clock time.
- Count the valid readings per band.
- Print one summary line per hour (00:00 to 07:00): the number of valid readings and their mean. Mark an hour that has broken lines. Use
range()with a step of 6. - Find the first reading below 19.5 °C and its time with a
forloop,breakand a loopelse. - Find the largest jump between consecutive valid readings with
zip(). - Decide the verdict with
if-elif-else. - Print the report below, exactly.
- End with at least three
assertchecks.
Sensor log quality report: data/readings.txt============================================Problems: line 12 (01:50): not a number 'error' line 24 (03:50): empty line 35 (05:40): not a number 'n/a'Lines: 43, valid: 40, broken: 3Bands: cool 11, normal 20, warm 9Hourly summary: 00:00 6 readings mean 21.68 °C 01:00 5 readings mean 22.64 °C (1 broken) 02:00 6 readings mean 22.02 °C 03:00 5 readings mean 21.00 °C (1 broken) 04:00 6 readings mean 19.83 °C 05:00 5 readings mean 19.70 °C (1 broken) 06:00 6 readings mean 20.58 °C 07:00 1 reading mean 21.10 °CAlarm: 19.3 °C at 05:20 (line 33)Largest jump: +1.2 °C into line 38Verdict: usable (7.0% broken lines)Step plan
Section titled “Step plan”-
Read the file. Store the lines in
lines. Printlen(lines)once to check that you have 43, then remove the print. -
Write the clock time of a line. Line
nis(n - 1) * 10minutes after midnight. Split the minutes with//and%as in module 01. -
Classify the lines. Loop with
enumerate(lines, start=1)andmatch line.split():.case []:is an empty line.case [word] if word.replace(".", "", 1).isdigit():is a valid number: one word made of digits and at most one decimal point.case _:is everything else. Collect the valid readings and their line numbers in two lists, and print a problem line for each broken line. -
Band the readings. Loop over the valid readings with an
if-elif-elsechain and count each band in a dict. -
Summarize each hour.
for start in range(0, len(lines), 6):gives the index of the first line of each hour.lines[start:start + 6]is the hour’s slice. Inside, loop over the slice, skip broken lines withcontinue, and accumulate a sum and a count. Guard the mean withif count:. -
Search for the alarm. Loop over the valid readings with their line numbers (
zip()).breakat the first one below the limit. Put the “no alarm” message in the loop’selse. -
Find the largest jump.
zip(readings[:-1], readings[1:])pairs each reading with the next one.readings[:-1]is every reading except the last. Track the largestabs()difference and where it happened. -
Decide the verdict. Compute the share of broken lines. A threshold decision is a job for
if-elif-else: testbroken == 0first, thenshare <= 0.10. -
Print the report and compare it line by line with the expected output.
-
Add self-checks that would catch a wrong count or a wrong formula.
A skeleton to start from:
# sensor_quality.py: a quality report for the raw sensor log.from pathlib import Path
INTERVAL_MINUTES = 10ALARM_BELOW = 19.5
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()readings = []reading_lines = []
# --- 1. Classify every line ---# TODO: enumerate the lines, match line.split(), print the problems,# collect the valid readings
# --- 2. Bands ---# TODO: count cool, normal and warm
# --- 3. Hourly summary ---# TODO: range(0, len(lines), 6) and a slice per hour
# --- 4. Alarm search ---# TODO: for ... break ... else
# --- 5. Largest jump ---# TODO: zip(readings[:-1], readings[1:])
# --- 6. Verdict ---# TODO: if, elif and else
# --- Self-checks ---# TODO: at least three assertsRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python sensor_quality.py runs with no error and prints the report |
| Line classification | 3 | match with sequence patterns and a guard; all 3 broken lines are reported with the right numbers and times; float() never sees a broken line |
| Bands and loop patterns | 2 | The band counts come from one if-elif-else chain inside a loop |
| Hourly summary | 3 | range() with a step and a guard against an empty hour; the means are correct |
| Search with loop else | 2 | break at the first alarm; the “not found” case uses the loop else |
| Largest jump | 2 | zip() pairs consecutive readings; abs() finds rises and drops |
| Verdict | 1 | if-elif-else, with the most specific test (broken == 0) first |
| Output and self-checks | 1 | The output equals the expected output; at least three meaningful asserts |
| Total | 16 | 13 or more: you are ready for module 04 |
Stretch goals
Section titled “Stretch goals”- Make the alarm limit a variable and run the search for 19.0 °C too. The loop
elsemust printAlarm: none below 19.0 °C. - Report the longest run of consecutive warm readings (see exercise M03-X01).
- Print a small text histogram of the bands, such as
cool | ########## 10, with"#" * count. - Add a
whileloop that reads the lines one by one and stops at the first line that contains the wordSTOP. Test it with a copy of the file. - Report lines with more than one word, such as
21.7 C, as a separate problem type: add a case[first, *rest]beforecase _:.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and comments can differ; your output must not.
Reference solution
# sensor_quality.py: a quality report for the raw sensor log data/readings.txt.# Assumption: the log starts at 00:00 and has one line every 10 minutes.import mathfrom pathlib import Path
INTERVAL_MINUTES = 10LINES_PER_HOUR = 60 // INTERVAL_MINUTESALARM_BELOW = 19.5
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()readings = [] # valid values, in file orderreading_lines = [] # the line number of each valid value
print("Sensor log quality report: data/readings.txt")print("=" * 44)
# --- 1. Classify every line ---------------------------------------------print("Problems:")for line_number, line in enumerate(lines, start=1): minutes = (line_number - 1) * INTERVAL_MINUTES clock = f"{minutes // 60:02d}:{minutes % 60:02d}" match line.split(): # split() also strips spaces and the line break case []: print(f" line {line_number:>2} ({clock}): empty") continue case [word] if word.replace(".", "", 1).isdigit(): readings.append(float(word)) reading_lines.append(line_number) case _: print(f" line {line_number:>2} ({clock}): not a number {line.strip()!r}") continue
broken = len(lines) - len(readings)print(f"Lines: {len(lines)}, valid: {len(readings)}, broken: {broken}")
# --- 2. Bands -----------------------------------------------------------bands = {"cool": 0, "normal": 0, "warm": 0}for reading in readings: if reading < 20.0: bands["cool"] += 1 elif reading <= 22.0: bands["normal"] += 1 else: bands["warm"] += 1print(f"Bands: cool {bands['cool']}, normal {bands['normal']}, warm {bands['warm']}")
# --- 3. Hourly summary --------------------------------------------------print("Hourly summary:")for start in range(0, len(lines), LINES_PER_HOUR): hour_total = 0.0 hour_count = 0 hour_broken = 0 for line in lines[start : start + LINES_PER_HOUR]: text = line.strip() if not text or not text.replace(".", "", 1).isdigit(): hour_broken += 1 continue hour_total += float(text) hour_count += 1 hour = start // LINES_PER_HOUR note = f" ({hour_broken} broken)" if hour_broken else "" if hour_count: mean = hour_total / hour_count word = "reading " if hour_count == 1 else "readings" print(f" {hour:02d}:00 {hour_count} {word} mean {mean:.2f} °C{note}") else: print(f" {hour:02d}:00 no valid readings{note}")
# --- 4. Alarm search ----------------------------------------------------for reading, line_number in zip(readings, reading_lines, strict=True): if reading < ALARM_BELOW: minutes = (line_number - 1) * INTERVAL_MINUTES alarm_clock = f"{minutes // 60:02d}:{minutes % 60:02d}" print(f"Alarm: {reading} °C at {alarm_clock} (line {line_number})") breakelse: # no break: no reading below the limit alarm_clock = None print(f"Alarm: none below {ALARM_BELOW} °C")
# --- 5. Largest jump ----------------------------------------------------largest_jump = 0.0jump_line = Nonefor before, after, line_number in zip( readings[:-1], readings[1:], reading_lines[1:], strict=True): change = after - before if abs(change) > abs(largest_jump): largest_jump = change jump_line = line_numberprint(f"Largest jump: {largest_jump:+.1f} °C into line {jump_line}")
# --- 6. Verdict ---------------------------------------------------------share = broken / len(lines)if broken == 0: verdict = "clean"elif share <= 0.10: verdict = "usable"else: verdict = "reject"print(f"Verdict: {verdict} ({share:.1%} broken lines)")
# --- Self-checks --------------------------------------------------------assert len(readings) + broken == len(lines)assert bands["cool"] + bands["normal"] + bands["warm"] == len(readings)assert min(readings) < ALARM_BELOW and alarm_clock == "05:20"assert math.isclose(sum(readings) / len(readings), 21.06, abs_tol=0.005)Sensor log quality report: data/readings.txt============================================Problems: line 12 (01:50): not a number 'error' line 24 (03:50): empty line 35 (05:40): not a number 'n/a'Lines: 43, valid: 40, broken: 3Bands: cool 11, normal 20, warm 9Hourly summary: 00:00 6 readings mean 21.68 °C 01:00 5 readings mean 22.64 °C (1 broken) 02:00 6 readings mean 22.02 °C 03:00 5 readings mean 21.00 °C (1 broken) 04:00 6 readings mean 19.83 °C 05:00 5 readings mean 19.70 °C (1 broken) 06:00 6 readings mean 20.58 °C 07:00 1 reading mean 21.10 °CAlarm: 19.3 °C at 05:20 (line 33)Largest jump: +1.2 °C into line 38Verdict: usable (7.0% broken lines)Run it from the project folder:
python sensor_quality.pyHow it works:
- Classify.
enumerate(lines, start=1)gives each line its number.line.split()turns the line into a list of words, so the shape of the line decides the case: no words, one numeric word (checked by the guard) or anything else. Thecontinuestatements make the skip explicit: nothing after thematchruns for a broken line, andfloat()only converts valid text. The two lists grow together, one item per valid line. - Bands. One
if-elif-elsechain per reading. Theelifneeds only the upper limit, because theifalready caught everything below 20.0. - Hours.
range(0, 43, 6)gives 0, 6, 12, …, 42: the index of the first line of each hour. The slicelines[start:start + 6]is that hour; the last slice is shorter (one line), and slicing past the end is safe. The guardif hour_count:would protect an hour without valid readings. A conditional expression picksreadingorreadings; the extra space afterreadingkeeps the columns aligned. - Alarm. The loop pairs each reading with its line number. It stops at the first reading below 19.5 °C: 19.3 °C on line 33, which is 320 minutes after midnight, so 05:20. If no reading were below the limit, the loop
elsewould print “none”. - Jump.
zip(readings[:-1], readings[1:], ...)pairs each reading with the next valid one.readings[:-1]drops the last reading, which has no successor, so all three inputs have 39 items andstrict=Trueholds. Plainzip(readings, readings[1:])gives the same pairs, becausezip()stops at the shorter input; the explicit form documents that you expect one pair fewer.abs()compares rises and drops fairly. The jump of +1.2 °C (19.5 to 20.7) leads into line 38. Broken lines are skipped, so a pair can span a gap. - Verdict. This is a threshold decision, so
if-elif-elsefits better thanmatch. The first test catches a perfect file. Theelifaccepts up to 10% broken lines. 3 of 43 lines is 7.0%, so the log isusable. - Self-checks. The asserts test invariants (the counts add up) and known facts of the dataset (the mean is 21.06 °C).
Alternative: you can classify each line once and store the result, for example a list of (line_number, text, status) tuples, then build the hourly summary from that list instead of checking each line twice. Module 04 shows tuples and lists of tuples; module 05 puts the line check into a function, so the rule lives in one place.