CP1 / COURSE HOME

Week 12 / Build a checkable report

Separate a missing reading from zero

Keep a failed measurement from becoming believable data.

Our functions work when their inputs meet the contract. Real incoming text also includes blanks and failure messages, so we need an outcome for those cases.

A teaching temperature stream contains “0”, “-12.5”, a blank and “ERROR”. Valid measurements must be finite numbers between −50 and 60 °C, including both limits.

Start with the problem

Try this first.

Sort the four records into valid readings and rejected records. If a conversion fails, would replacing it with zero preserve what happened?

Why this week's tool?

try/except handles failed conversion. Separate validity checks handle nonfinite or out-of-range numbers. A reason accompanies each rejection.

By the end: Keep valid zero and negative temperatures while distinguishing them from records that could not be measured or interpreted.

The idea behind the program

Conversion and validity are different

float('nan') and float('inf') can succeed. That does not make the result a useful temperature. Check finiteness after conversion, then the sensor-specific range. A conversion exception covers only one kind of invalid input.

Missingness has meaning

Replacing an invalid reading with zero manufactures a measurement. Zero is a valid temperature here, so it must remain distinguishable from missing data. Use a separate validity flag and a reason; only retained values enter the mean.

Catch what you understand

Catch ValueError for malformed numeric text. A blanket except can hide unrelated programming errors. The function below expects a string; callers must honour that contract rather than relying on a broad catch to conceal mistakes.

A short Python example

Read the example alongside the explanation. Run it in a new notebook cell and change one input to see how it behaves.

import math

def validate_temperature(text):
    if not text.strip():
        return False, 'empty value'
    try:
        value = float(text)
    except ValueError:
        return False, 'non-numeric value'
    if not math.isfinite(value):
        return False, 'nonfinite value'
    if not -50 <= value <= 60:
        return False, 'out of range'
    return True, value

for text in ['0', '-10', '', 'nan', '61']:
    print(repr(text), validate_temperature(text))

Example output

'0' (True, 0.0)
'-10' (True, -10.0)
'' (False, 'empty value')
'nan' (False, 'nonfinite value')
'61' (False, 'out of range')

Invalid data is a different state from zero

Error handling should preserve the meaning of valid observations. A conversion failure, a nonfinite number and an out-of-range reading require explicit handling; replacing them with zero invents measurements.

Draw or trace

Trace four inputs: "0", "20", "missing" and "nan". Separate conversion, finiteness and allowed-range checks before admitting a value to a summary.

Predict before running. If missing data becomes zero, how does the average of the valid readings 0 and 20 change?

Trace and explanation — after your prediction
  1. With only the two valid readings, total = 20 and count = 2, giving mean 10.
  2. Replacing one missing value with zero changes count to 3 and gives about 6.67.
  3. A successful float conversion of "nan" still needs a finiteness check.

Zero is valid when the sensor contract permits it; missing data is not a zero reading. Catch the relevant exception, record or report the failure, and define the all-invalid case without dividing by zero.

Change one thing. Change every row to invalid data. Specify the report’s no-data message before running the program.

Türkçe: Eksik veriyi sıfır yapmak ölçüm uydurur ve ortalamayı değiştirir. Dönüşüm, sonluluk ve aralık denetimleri ayrı adımlardır.

Examples and variations

Each example changes something about the same problem. Open the ones you want to explore and follow the worked explanation.

01Real zero and negative

Input strings '0' and '-10'; valid band −50–60 °C

Question: Are either of these values missing or invalid?

  1. Both convert to finite floats
  2. Both lie inside the inclusive band
  3. Keep 0 and −10 as measurements

Both accepted

A generic rule that rejects all nonpositive values would discard valid temperatures.

02Nonfinite value

Input string 'nan'

Question: Does successful float conversion imply validity?

  1. float('nan') succeeds
  2. math.isfinite(value) is False
  3. Reject before calculating statistics

REJECT: nonfinite value

An exception handler alone does not catch every unusable reading.

03Zero-substitution fault

Input ['20', 'error', '22']; compare rejection with replacement by zero

Question: How does replacing the error change the mean?

  1. Reject invalid: retained [20, 22]; mean 21 °C
  2. Replace with zero: [20, 0, 22]; mean 14 °C
  3. The substituted zero was never measured

Honest mean 21 °C from 2 readings; 1 rejected

Always report retained and rejected counts. If none remain, report no valid data instead of a fabricated mean.

See the Colab code run

Interactive walkthroughs of Error Handling. Enable JavaScript to step through code, variables, collections and output. The companion notebook remains available below.

Work on it in Colab

Use the notebook to try the ideas yourself. The steps below connect this week's example to the programming practice.

  1. Write a decision table for blank, malformed, nonfinite, out-of-range and valid input. Give each rejected class a reason.
  2. Test −50, 60 and values just outside the band, plus 0, −10, abc, nan and inf.
  3. Compare the two means in the zero-substitution case by hand. Explain the changed denominator.
  4. Consider a batch containing only invalid records. Specify what the report should say before writing summary code.

Something to take away: A validation table covering every fault class and a report that separates valid zeros, rejected values and an empty valid group.

Suggested exercises, downloads & solutions

Read the notebook's teaching cells before these exercises.

  • EX05 Safe Division Function (Medium)
  • EX06 Validate and Convert (Medium)
  • EX07 Robust Average (Medium)
  • EX08 Temperature Converter with Full Validation (Medium)
Download notebookWorked solutions

Use the notebook's core and optional labels to choose your workload. This activity fits within guided class time.

Optional notes & guidance
My notes
Using AI or working with a partner

Ask AI for robust temperature parsing. Challenge any broad except, zero fallback or positive-only filter. Independently include nan, inf and the exact range endpoints in your tests.

You can also review the supplied example with a partner. Use the same inputs to compare the reasoning. Follow the syllabus rules for assessed work.