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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Your script must:
- 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 asstr. - Convert the six raw values to
float. - Compute the minimum, maximum, range (max − min) and mean in °C, and the mean in °F (°F = °C × 9 / 5 + 32).
- Compute the change from the first to the last reading.
- Compute the clock time of the last reading with
//and%. Do not type it in. - Compute two
boolflags: all readings are inside the valid range, and the room got warmer. - Print the report below, exactly. Use f-strings for every number.
- Explain the non-obvious lines with comments: units, sources and reasons.
- End with at least two
assertchecks that would catch a wrong formula.
The expected report:
Sensor report: S1 (server room)-------------------------------First reading: 06:00Last reading: 06:50Readings: 6 (every 10 minutes)Min: 19.5 °CMax: 21.2 °CRange: 1.7 °CMean: 20.58 °C (69.05 °F)Change first to last: +1.3 °CAll in range 19.0-23.0 °C: TrueWarming: TrueStep plan
Section titled “Step plan”-
Create the file. Make
sensor_report.pyin your project folder. Add a comment at the top that says what the script does and where the data comes from. -
Store the inputs. Write one assignment per input. Keep the raw readings as strings, with the
\non the last one. -
Convert. Make six
floatvariables from the six strings. Print one of them withtype()to check, then remove that line. -
Compute the statistics. Use
min()andmax()with six arguments. Put the sum in parentheses before you divide by the count. -
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 - 1intervals later. Split the result into hours and minutes with//and%. -
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.
-
Print the report. Use
:.1fand:.2ffor decimals,:02dfor the clock times and:+.1ffor the change. The+in:+.1falways shows the sign, so a rise reads+1.3. -
Add self-checks. Assert that the mean lies between the minimum and the maximum, and that the last reading is at 06:50.
-
Run it with
python sensor_report.py. Compare every line with the expected report.
A skeleton to start from:
# 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 statementsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- 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. - Report the minimum and maximum in °F too.
- 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.5for 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). - Add a flag that is
Truewhen any reading is more than 1.0 °C away from the mean. Useabs(). - Make a copy of the script that asks for the sensor id with
input(). Remember thatinput()returns astr.
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_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:00start_minute = 0interval_minutes = 10 # the sensor logs every 10 minuteslow_limit = 19.0 # valid range from the sensor's data sheet, in °Chigh_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 - lowestmean_c = (r1 + r2 + r3 + r4 + r5 + r6) / countmean_f = mean_c * 9 / 5 + 32change = 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_minutelast_total = start_total + (count - 1) * interval_minuteslast_hour = last_total // 60last_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_limitwarming = 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 <= highestassert math.isclose(mean_c, 123.5 / 6)assert (last_hour, last_minute) == (6, 50)Sensor report: S1 (server room)-------------------------------First reading: 06:00Last reading: 06:50Readings: 6 (every 10 minutes)Min: 19.5 °CMax: 21.2 °CRange: 1.7 °CMean: 20.58 °C (69.05 °F)Change first to last: +1.3 °CAll in range 19.0-23.0 °C: TrueWarming: TrueRun it from the project folder:
python sensor_report.pyHow it works:
- Inputs. Every value that could change tomorrow is a named variable at the top. To report on another shift, you edit only this block.
- Convert.
float()turns each raw string into a number and ignores the trailing\n. - Statistics.
min()andmax()give the extremes. The range is their difference. The mean divides the sum, in parentheses, by the count. - Time. 06:00 is 360 minutes after midnight. Five more intervals of 10 minutes give 410 minutes.
410 // 60is 6 hours and410 % 60is 50 minutes, so the last reading is at 06:50. - 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
warmingisTrue. - Report. The format specs control every number:
:.1f,:.2f,:02dand:+.1f. The range is really1.6999999999999993and the change1.3000000000000007; the specs hide these float errors. - 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.