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.


Python
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, skipped


Python 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.


Flowchart in which a try box branches to an except ValueError box when the conversion raises and to an else box when it does not, with both branches leading to the next item.


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:


mean=23.03=7.666…\text{mean} = \frac{23.0}{3} = 7.666\ldots


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.010.0 / 2 = 5.0 and the call returns (5.0, 1).



A student runs the short Python program below. Which lines does the program print, in order, by the time it finishes running?


Python
try:
    n = int("4x")
    print("A")
except ValueError:
    print("B")
print("C")
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


Python
def safe_quotient(a, b):
    try:
        result = int(a) // int(b)
    except ValueError:
        result = -1
    except ZeroDivisionError:
        result = 0
    return result
abReturned value
175
170
x0
124.0
05

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice