Skip to content

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.

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

Your script must:

  1. Read the lines of data/readings.txt with Path(...).read_text(encoding="utf-8").splitlines().
  2. Classify every line as empty, invalid or valid, with its line number. Use match text.split(): with sequence patterns and a guard, and continue to skip broken lines.
  3. Print one problem line per broken line, with its line number and clock time.
  4. Count the valid readings per band.
  5. 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.
  6. Find the first reading below 19.5 °C and its time with a for loop, break and a loop else.
  7. Find the largest jump between consecutive valid readings with zip().
  8. Decide the verdict with if-elif-else.
  9. Print the report below, exactly.
  10. End with at least three assert checks.
Expected output
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: 3
Bands: cool 11, normal 20, warm 9
Hourly 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 °C
Alarm: 19.3 °C at 05:20 (line 33)
Largest jump: +1.2 °C into line 38
Verdict: usable (7.0% broken lines)
  1. Read the file. Store the lines in lines. Print len(lines) once to check that you have 43, then remove the print.

  2. Write the clock time of a line. Line n is (n - 1) * 10 minutes after midnight. Split the minutes with // and % as in module 01.

  3. Classify the lines. Loop with enumerate(lines, start=1) and match 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.

  4. Band the readings. Loop over the valid readings with an if-elif-else chain and count each band in a dict.

  5. 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 with continue, and accumulate a sum and a count. Guard the mean with if count:.

  6. Search for the alarm. Loop over the valid readings with their line numbers (zip()). break at the first one below the limit. Put the “no alarm” message in the loop’s else.

  7. 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 largest abs() difference and where it happened.

  8. Decide the verdict. Compute the share of broken lines. A threshold decision is a job for if-elif-else: test broken == 0 first, then share <= 0.10.

  9. Print the report and compare it line by line with the expected output.

  10. Add self-checks that would catch a wrong count or a wrong formula.

A skeleton to start from:

sensor_quality.py (starter)
# sensor_quality.py: a quality report for the raw sensor log.
from pathlib import Path
INTERVAL_MINUTES = 10
ALARM_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 asserts
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
  1. Make the alarm limit a variable and run the search for 19.0 °C too. The loop else must print Alarm: none below 19.0 °C.
  2. Report the longest run of consecutive warm readings (see exercise M03-X01).
  3. Print a small text histogram of the bands, such as cool | ########## 10, with "#" * count.
  4. Add a while loop that reads the lines one by one and stops at the first line that contains the word STOP. Test it with a copy of the file.
  5. Report lines with more than one word, such as 21.7 C, as a separate problem type: add a case [first, *rest] before case _:.

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
# 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 math
from pathlib import Path
INTERVAL_MINUTES = 10
LINES_PER_HOUR = 60 // INTERVAL_MINUTES
ALARM_BELOW = 19.5
lines = Path("data/readings.txt").read_text(encoding="utf-8").splitlines()
readings = [] # valid values, in file order
reading_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"] += 1
print(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})")
break
else: # no break: no reading below the limit
alarm_clock = None
print(f"Alarm: none below {ALARM_BELOW} °C")
# --- 5. Largest jump ----------------------------------------------------
largest_jump = 0.0
jump_line = None
for 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_number
print(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)
Output
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: 3
Bands: cool 11, normal 20, warm 9
Hourly 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 °C
Alarm: 19.3 °C at 05:20 (line 33)
Largest jump: +1.2 °C into line 38
Verdict: usable (7.0% broken lines)

Run it from the project folder:

Terminal
python sensor_quality.py

How it works:

  1. 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. The continue statements make the skip explicit: nothing after the match runs for a broken line, and float() only converts valid text. The two lists grow together, one item per valid line.
  2. Bands. One if-elif-else chain per reading. The elif needs only the upper limit, because the if already caught everything below 20.0.
  3. Hours. range(0, 43, 6) gives 0, 6, 12, …, 42: the index of the first line of each hour. The slice lines[start:start + 6] is that hour; the last slice is shorter (one line), and slicing past the end is safe. The guard if hour_count: would protect an hour without valid readings. A conditional expression picks reading or readings; the extra space after reading keeps the columns aligned.
  4. 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 else would print “none”.
  5. 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 and strict=True holds. Plain zip(readings, readings[1:]) gives the same pairs, because zip() 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.
  6. Verdict. This is a threshold decision, so if-elif-else fits better than match. The first test catches a perfect file. The elif accepts up to 10% broken lines. 3 of 43 lines is 7.0%, so the log is usable.
  7. 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.