Context managers · 10 / 15 Exercise Medium

Ignore errors

Objective

Create a Python program that adds up numbers while ignoring texts that are not numbers, using suppress from the contextlib module instead of a try/except.

Instructions

  • Read an integer n and then n texts. Inside with suppress(ValueError) try to convert each text to an integer with int, add it up and count it as valid.
  • Compute the average (sum divided by valid count) inside another suppress(ZeroDivisionError) block for the case where there are no valid values.
  • Show Valid: v, Ignored: i, Sum: s and Average: m (with 2 decimals), or Average: no data if none was valid.
Input
4
10
x
5
2.5
Output
Valid: 2
Ignored: 2
Sum: 15
Average: 7.50

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise