try/except Blocks
Example: Averaging sensor readings that may be malformed
A weather station logs temperatures as text, and some entries are corrupted. The function below converts each entry with float(), skips any entry it cannot convert, and returns the mean of the good readings together with the number of entries it skipped.
def average_readings(raw):
total = 0.0
count = 0
skipped = 0
for item in raw:
try:
value = float(item)
except ValueError:
skipped += 1
else:
total += value
count += 1
try:
mean = total / count
except ZeroDivisionError:
mean = None
return mean, skippedPython watches the code inside try. If a statement there raises an exception whose type matches an except clause, Python abandons the rest of the try block and jumps to that clause, the exception handler, and the program then carries on after the whole statement instead of stopping. An except clause catches only the exception types it names; an exception that matches no handler keeps travelling up to whoever called the function. The optional else block runs only when the try block finished without raising anything.
a) Find the value returned by average_readings(["12.5", "abc", "7", " ", "3.5"]).
Trace each item through the inner try statement.
- "12.5" converts to 12.5, so the else block adds it to the total and counts it.
- "abc" makes float() raise ValueError; the handler adds 1 to skipped, and the else block does not run.
- "7" converts to 7.0 and is added and counted.
- " " holds only whitespace, which float() cannot convert, so it also raises ValueError and is skipped.
- "3.5" converts to 3.5 and is added and counted.
Adding the three converted values gives a total of ________ over a count of ________, and the two failed conversions leave skipped at ________. The count is not zero, so the second try block divides without raising:
The function returns (7.666666666666667, 2): a mean of about 7.67 with two entries skipped.
b) Find the value returned by average_readings(["n/a", "--"]).
Both strings make float() raise ValueError, so the handler increments skipped each time and the else block never runs. After the loop, count is still ________ and the total is still 0.0.
The second try statement now evaluates 0.0 / 0. Dividing by zero raises ________, which matches the second handler, so mean is set to None instead of the program crashing. The function returns (None, 2).
c) A colleague calls average_readings(["4", None, "6"]) and the program crashes. Explain why no handler caught the problem, then change one line of the function so that this call returns (5.0, 1).
The string "4" converts normally, so the total is 4.0 and the count is 1. Next, float(None) raises ________, because None is neither a string nor a number. The only handler in the loop names ValueError, and a TypeError does not match it, so the exception leaves the try statement unhandled, ends the function early, and Python prints a traceback. The item "6" is never processed.
To handle both problems, replace the line except ValueError: with except (ValueError, TypeError):. A tuple of types makes one handler match either exception.
With that change, None is counted as skipped and the loop continues. Converting "4" and "6" gives a total of ________ over a count of 2, so the mean is 10.0/2=5.0 and the call returns (5.0, 1).
A Python 3 ticket-entry form converts the string entry to an integer. If conversion raises ValueError, the form must store the exception's message and continue running. Fill each blank with the appropriate Python keyword.
Place seats = int(entry) inside a block. Begin its matching handler with followed by ValueError. To give the caught exception the name problem, put between ValueError and problem. Inside the handler, use message = str(problem) to store the message.
The Python function below divides two whole numbers that arrive as strings from a web form. Both arguments are always strings; the table shows the characters of each string without quotation marks. For each pair of arguments, enter the integer that the function returns.
def safe_quotient(a, b):
try:
result = int(a) // int(b)
except ValueError:
result = -1
except ZeroDivisionError:
result = 0
return result| a | b | Returned value |
| 17 | 5 | |
| 17 | 0 | |
| x | 0 | |
| 12 | 4.0 | |
| 0 | 5 |