Skip to content

01. Python basics — Mini-project

You look after a temperature sensor in a server room. Every morning, a technician copies the readings of the first hour of the morning shift and asks the same questions: how warm was it, how much did it change, and did any reading leave the safe range?

Write a script, sensor_report.py, that answers these questions in a short report. The script must run with one command, python sensor_report.py, so that anyone can rerun it with new values.

The project uses every part of module 01: a script, variables, the five basic types, arithmetic with // and %, comparisons, logical operators, type conversion, f-strings and comments.

The values come from data/readings.txt. The file 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).

This project uses lines 37 to 42, a stretch with no broken lines:

Line Raw text Time
37 19.5 06:00
38 20.7 06:10
39 20.1 06:20
40 21.2 06:30
41 21.2 06:40
42 20.8 06:50

Copy them into your script as strings, exactly as a program would read them from the file. A line read from a file ends with a line break, so write the last value as "20.8\n". Module 07 reads the whole file for you, and module 06 skips the broken lines.

The sensor logs a reading every 10 minutes. Its data sheet gives a valid range of 19.0 °C to 23.0 °C.

Your script must:

  1. Store all inputs in clearly named variables: the sensor id S1, the location, the start time (06:00), the interval (10 minutes), the two range limits and the six raw values as str.
  2. Convert the six raw values to float.
  3. Compute the minimum, maximum, range (max − min) and mean in °C, and the mean in °F (°F = °C × 9 / 5 + 32).
  4. Compute the change from the first to the last reading.
  5. Compute the clock time of the last reading with // and %. Do not type it in.
  6. Compute two bool flags: all readings are inside the valid range, and the room got warmer.
  7. Print the report below, exactly. Use f-strings for every number.
  8. Explain the non-obvious lines with comments: units, sources and reasons.
  9. End with at least two assert checks that would catch a wrong formula.

The expected report:

Expected output
Sensor report: S1 (server room)
-------------------------------
First reading: 06:00
Last reading: 06:50
Readings: 6 (every 10 minutes)
Min: 19.5 °C
Max: 21.2 °C
Range: 1.7 °C
Mean: 20.58 °C (69.05 °F)
Change first to last: +1.3 °C
All in range 19.0-23.0 °C: True
Warming: True
  1. Create the file. Make sensor_report.py in your project folder. Add a comment at the top that says what the script does and where the data comes from.

  2. Store the inputs. Write one assignment per input. Keep the raw readings as strings, with the \n on the last one.

  3. Convert. Make six float variables from the six strings. Print one of them with type() to check, then remove that line.

  4. Compute the statistics. Use min() and max() with six arguments. Put the sum in parentheses before you divide by the count.

  5. Compute the time of the last reading. Turn 06:00 into minutes since midnight. The first reading is at the start, so the last one comes count - 1 intervals later. Split the result into hours and minutes with // and %.

  6. Build the flags. Every reading is in range when the lowest one is at least the low limit and the highest one is at most the high limit. The room got warmer when the change is greater than 0.

  7. Print the report. Use :.1f and :.2f for decimals, :02d for the clock times and :+.1f for the change. The + in :+.1f always shows the sign, so a rise reads +1.3.

  8. Add self-checks. Assert that the mean lies between the minimum and the maximum, and that the last reading is at 06:50.

  9. Run it with python sensor_report.py. Compare every line with the expected report.

A skeleton to start from:

sensor_report.py (starter)
# sensor_report.py: a shift report for one temperature sensor.
# --- Inputs ---
sensor_id = "S1"
# TODO: location, start time, interval, limits, six raw readings as str
# --- Convert ---
# TODO: six float values
# --- Compute ---
# TODO: min, max, range, mean in °C and °F, change, time of the last reading, flags
# --- Report ---
# TODO: print the report with f-strings
# --- Self-checks ---
# TODO: at least two assert statements
Criterion Points Full points when
Runs as a script 2 python sensor_report.py runs with no error and prints the report
Correct numbers 3 Every value matches the expected report
Type conversion 2 The six raw values are str and are converted with float()
Time arithmetic 2 The last reading time comes from // and %, not a typed value
Flags 2 Both flags are bool values from comparisons; the range flag uses and
Output format 2 f-strings with format specs; the output equals the expected report
Readability 2 snake_case names that say what each value means; comments explain units and reasons
Self-checks 1 At least two meaningful assert statements
Total 16 13 or more: you are ready for module 02
  1. Add a second hour of readings (lines 1 to 6 of data/readings.txt) as a second sensor shift and print a line that says which shift was warmer on average.
  2. Report the minimum and maximum in °F too.
  3. Compute the population standard deviation, a measure of how far readings spread around the mean: the square root of the average squared distance from the mean. Use ** 0.5 for the square root. For lines 37 to 42, it is about 0.61 °C. pandas .std() divides by n − 1 instead of n and gives about 0.67 °C (module 29 explains why).
  4. Add a flag that is True when any reading is more than 1.0 °C away from the mean. Use abs().
  5. Make a copy of the script that asks for the sensor id with input(). Remember that input() returns a str.

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_report.py
# sensor_report.py: a shift report for one temperature sensor.
# The raw values are lines 37-42 of data/readings.txt, copied as text.
# Module 07 reads them from the file; here they are typed in by hand.
import math
# --- Inputs ------------------------------------------------------------
sensor_id = "S1"
location = "server room"
start_hour = 6 # first reading at 06:00
start_minute = 0
interval_minutes = 10 # the sensor logs every 10 minutes
low_limit = 19.0 # valid range from the sensor's data sheet, in °C
high_limit = 23.0
raw_1 = "19.5"
raw_2 = "20.7"
raw_3 = "20.1"
raw_4 = "21.2"
raw_5 = "21.2"
raw_6 = "20.8\n" # a line read from a file still ends with a line break
# --- Convert -----------------------------------------------------------
r1 = float(raw_1)
r2 = float(raw_2)
r3 = float(raw_3)
r4 = float(raw_4)
r5 = float(raw_5)
r6 = float(raw_6) # float() ignores the trailing "\n"
count = 6
# --- Compute -----------------------------------------------------------
lowest = min(r1, r2, r3, r4, r5, r6)
highest = max(r1, r2, r3, r4, r5, r6)
spread = highest - lowest
mean_c = (r1 + r2 + r3 + r4 + r5 + r6) / count
mean_f = mean_c * 9 / 5 + 32
change = r6 - r1 # positive means the room got warmer during the shift
# Time of the last reading: the first is at the start, so add count - 1 steps.
start_total = start_hour * 60 + start_minute
last_total = start_total + (count - 1) * interval_minutes
last_hour = last_total // 60
last_minute = last_total % 60
# Range checks: with lowest and highest inside the limits, every reading is.
all_in_range = low_limit <= lowest and highest <= high_limit
warming = change > 0
# --- Report ------------------------------------------------------------
title = f"Sensor report: {sensor_id} ({location})"
print(title)
print("-" * len(title))
print(f"First reading: {start_hour:02d}:{start_minute:02d}")
print(f"Last reading: {last_hour:02d}:{last_minute:02d}")
print(f"Readings: {count} (every {interval_minutes} minutes)")
print(f"Min: {lowest:.1f} °C")
print(f"Max: {highest:.1f} °C")
print(f"Range: {spread:.1f} °C")
print(f"Mean: {mean_c:.2f} °C ({mean_f:.2f} °F)")
print(f"Change first to last: {change:+.1f} °C")
print(f"All in range {low_limit}-{high_limit} °C:", all_in_range)
print("Warming:", warming)
# --- Self-checks -------------------------------------------------------
assert lowest <= mean_c <= highest
assert math.isclose(mean_c, 123.5 / 6)
assert (last_hour, last_minute) == (6, 50)
Output
Sensor report: S1 (server room)
-------------------------------
First reading: 06:00
Last reading: 06:50
Readings: 6 (every 10 minutes)
Min: 19.5 °C
Max: 21.2 °C
Range: 1.7 °C
Mean: 20.58 °C (69.05 °F)
Change first to last: +1.3 °C
All in range 19.0-23.0 °C: True
Warming: True

Run it from the project folder:

Terminal
python sensor_report.py

How it works:

  1. Inputs. Every value that could change tomorrow is a named variable at the top. To report on another shift, you edit only this block.
  2. Convert. float() turns each raw string into a number and ignores the trailing \n.
  3. Statistics. min() and max() give the extremes. The range is their difference. The mean divides the sum, in parentheses, by the count.
  4. Time. 06:00 is 360 minutes after midnight. Five more intervals of 10 minutes give 410 minutes. 410 // 60 is 6 hours and 410 % 60 is 50 minutes, so the last reading is at 06:50.
  5. Flags. If the lowest reading is at least 19.0 and the highest is at most 23.0, every reading lies between them. Two comparisons check all six values. The change is +1.3 °C, so warming is True.
  6. Report. The format specs control every number: :.1f, :.2f, :02d and :+.1f. The range is really 1.6999999999999993 and the change 1.3000000000000007; the specs hide these float errors.
  7. Self-checks. The asserts test rules that must always hold. If you break the mean formula, for example by dropping the parentheses, the first assert stops the script.

Alternative: you could compute the last reading time as a float with / and then split it, but every step would need int() and could carry float errors. // and % on whole minutes keep the arithmetic exact. Later modules replace the six variables with a list (module 04), a loop (module 03) and a file read (module 07), and the report logic stays the same.