25 XP

46. Add up the valid numbers

Beginner exceptions strings

Data typed in by people is messy: a column of prices might hold "12", "4.50", "n/a" and an empty cell.

Write a function add_valid(items) that takes a list of strings and returns the total of those that are numbers, as a float. A string is a number when float() can read it: whole numbers, decimals, a sign in front, spaces around it and forms like "1e3" (1000) all count. Skip every string that isn't one, such as "abc", "", "3 apples" or "1,000".

If no string is a number, or the list is empty, the total is 0.0.

Example 1

Inputitems = ["3", "4.5", "abc"]
Output7.5
Explanation"abc" isn't a number; 3 + 4.5 = 7.5.

Example 2

Inputitems = ["10", "", "-2", "two"]
Output8.0
ExplanationThe empty string and "two" are skipped.

Example 3

Inputitems = []
Output0.0
ExplanationNothing to add.

Constraints

  • items has 0 to 50 strings, each 0 to 20 characters long.
  • None of them is a word float() reads as a special value, such as "inf" or "nan".

Submit also runs 8 more tests you can't see.

Practises Errors and Exceptions (lesson 21).

Code
def add_valid(items):
    """Add up the strings that are numbers.

    items: list of str; may be empty
    Returns: float, the total of the strings float() can
        read, skipping the rest
    """
    # Write your code here
    pass