46. Add up the valid numbers
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
items = ["3", "4.5", "abc"]7.5Example 2
items = ["10", "", "-2", "two"]8.0Example 3
items = []0.0Constraints
itemshas 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).
float("4.5")gives4.5, butfloat("abc")raises aValueError. Let it try, and catch the error when it comes.- Put the
try:andexcept ValueError:inside the loop, around the one item: atryaround the whole loop would stop at the first bad item and skip all the rest. - Checks like
item.isdigit()miss"-2"and"4.5": askingfloat()itself is the reliable test. Start the total at0.0.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.