1.Why should I care?
Real logs contain blank lines, error codes and impossible values. A program that crashes on the first one is useless; a program that silently turns them into zeros is dangerous. Defensive checks make software that keeps working and tells you the truth about its data.
- ◇ Use try / except ValueError to handle a line that cannot be converted to a number.
- ◇ Add range (plausibility) checks based on the sensor's rated range.
- ◇ Count and report rejected data rather than silently discarding it.
2.Discover
In the Code Lab, type parse_reading from this lesson and run it on the sample lines. Then add your own nasty lines (" 21.5 ", "21,5", "nan", "1e3") and predict what each does before running. Which ones slip through, and how would you stop them?
Can't use the interactive? Read a description instead
The Code Lab exercise can be traced by hand. parse_reading returns the number for '21.5' and '22.1'; None for 'ERR' and '' (float fails); and None for '-999.0' (outside −40 to 125). So good = [21.5, 22.1] and 3 of 5 lines are rejected. ' 21.5 ' converts (float ignores surrounding spaces) and '21,5' fails.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1 · a fresh version every time
A log has the lines ["-999.0","25.8","-999.0","21.4","21.6","19.1","20.0","--"]. The program keeps a line only if float(line) works and -40 <= value <= 125 (the sensor's rated range, °C); otherwise it skips it. How many readings are kept?
Practice 2
Which check rejects the line "130.5" from a sensor rated −40 to 125 °C?
4.Apply it
Extend parse_reading to reject nan, then write four asserts (a good line, ERR, blank and −999.0). Use it in your log program and print how many lines were rejected out of the total.
5.Understand
Validate every line
def parse_reading(line):
"""Return the reading in °C, or None if the line is not a plausible reading."""
try:
value = float(line)
except ValueError:
return None
if value < -40 or value > 125:
return None
return value
lines = ["21.5", "ERR", "", "-999.0", "22.1"]
good = []
for line in lines:
value = parse_reading(line)
if value is not None:
good.append(value)
print(good) # [21.5, 22.1]Two different checks
The conversion check (try / except ValueError) catches lines that are not numbers at all: ERR, blanks, '--'. The plausibility check catches numbers that cannot be real: −999.0, 130.5. The band comes from the sensor's datasheet (here −40 to 125 °C, typical of small temperature sensors) or from physics.
Never hide the evidence
Count what you reject and report it: '3 of 480 lines rejected'. Never replace bad lines with 0, which drags the mean down and looks like a real reading. Catch only the error you expect (except ValueError), not every error, so genuine bugs still show up.
Explain it another way
A bouncer at a door: first check it is a ticket at all, then check it is for tonight. People without one are turned away and counted, not let in as 'nobody'.
try / except handles a specific exception locally; the function's contract (return a float or None) is documented in the docstring. Validation at the boundary keeps the rest of the program working on clean, typed data.
Industrial and scientific data pipelines always have this stage, often called input validation or data cleaning, and keep counts of rejected records as a health signal for the sensors.
Worked example 1
What does parse_reading do with "nan"?
float("nan") succeeds and returns nan (not a number). Both nan < -40 and nan > 125 are False, so the range check lets it through! Add import math and if math.isnan(value): return None, or write the range check as if not (-40 <= value <= 125): return None, which rejects nan because the chained comparison is False.
Common mix-ups
- If float() succeeds, the reading is good.
✓ −999.0 and 130.5 convert fine but are impossible. Range checks are also needed. - Catching every exception makes a program robust.
✓ It makes bugs invisible. Catch the specific errors you expect and handle them deliberately.
6.Watch
→ Watch how try and except catch a specific error, and why catching only the error you expect is safer than catching everything.
How try and except let a program handle bad input, such as a malformed line in a log, without crashing.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
Why is replacing bad lines with 0 a bad idea?
Practice 4
Why write except ValueError rather than a bare except?
8.Predict
A log line is -999.0, a common 'no reading' code. What does float("-999.0") do?
Guess first. Being wrong here is how the surprise works.
9.Reflect
10.Go further
- Python tutorial: handling exceptions ↗The official guide to try and except.
Concepts: Testing and debugging · How sensors measure