0

The question is to iterate through the list and calculate and return the sum of any numeric values in the list.

That's all I've written so far...

def main():
    my_list = input("Enter a list: ")
    total(my_list)

def total(my_list1):
    list_sum = 0 
    try:
        for number in my_list1:
            list_sum += number
    except ValueError:
         #don't know what to do here

    print list_sum

main()
user3161743
  • 161
  • 4
  • 8
  • 13
  • Think about when does the `ValueError` happen and what do you want to do when it happens (skip? [continue? pass?](http://docs.python.org/2/tutorial/controlflow.html)). What made you decide to put the for loop inside instead of outside the try/except. – kalhartt Jan 05 '14 at 22:43
  • You shouldn't completely re-write your question in such a way. If you have any further information then please edit it and add it to the end. – Ffisegydd Jan 05 '14 at 23:06
  • Please stop deleting content from your questions. I've had to revert three edits on all three of your questions. Thanks – TerryA Jan 05 '14 at 23:21

4 Answers4

3

You can use a generator expression such that:

from numbers import Number

a = [1,2,3,'sss']

sum(x for x in a if isinstance(x,Number)) # 6

This will iterate over the list and check whether each element is int/float using isinstance()

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
3

If you check to see whether the list item is an int, you can use a generator:

>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6
Community
  • 1
  • 1
Ben
  • 51,770
  • 36
  • 127
  • 149
1

Maybe try and catch numerical

this seams to work:

data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:   
    try:
        if float(d):
            result.append(d)
    except:
        pass    

print sum(result) #25, it is equal to 1+2+3+4+5+6+4
PyWebDesign
  • 187
  • 1
  • 11
0

Using the generator removes the need for the below line but as a side note, when you do something like this for this:

try:
    for number in my_list1:
        list_sum += number
except ValueError:
     #don't know what to do here

You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.

def main():
    my_list = input("Enter a list: ")
    total(my_list)
    return

def total(my_list1):
    list_sum = 0 
    try:
        for number in my_list1:
            list_sum += float(number)
    except ValueError:
        print "Error"
    return list_sum

if __name__ == "__main__":
    main()
grandocu
  • 326
  • 1
  • 4