1

I am trying to solve the following question:

Define a function sum() and a function multiply() that sums and multiplies(respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply ([1, 2, 3, 4]) should return 24.

So far I have the following:

def sums(listofnums):
    total=0
    for i in (listofnums):
        total=total+i
    return total

def multiply(listofnums):
     total =1
     for i in (listofnums):
         total = total*i
     return total

 listofnums=[]
 nums=input("Enter a list of numbers seperated by commas: ").split(",")
 nums2=[float(i) for i in nums]
 listofnums.append(nums2)

 print(listofnums)
 print (sums(listofnums))
 print (multiply(listofnums))

This returns the following:

 *Enter a list of numbers seperated by commas: 1,2,3
 [[1.0, 2.0, 3.0]]
 Traceback (most recent call last):
 File "C:\Python34\46 simple python ex\sum() and mult() v2.py", line 19, in <module>
print (sums(listofnums))
   File "C:\Python34\46 simple python ex\sum() and mult() v2.py", line 4, in sums
total=total+i
 TypeError: unsupported operand type(s) for +: 'int' and 'list'*

I suspect the issue is that my functions sums and multiply only work with a list of the form(x,x,x,x) or [x,x,x,x] and what values I am returning are [[x,x,x]].

How can I fix this?

(Note I think that the rest of the code is fine b/c when I manually input a set of numbers of the form [x,x,x] directly in the code it works fine.)

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • Simple, Use `listofnums.extend(nums2)` instead of `listofnums.append(nums2)` – Bhargav Rao Jul 22 '15 at 16:40
  • Thank you a lot!, sorry for the duplicate I did not know how to ask the question in such a manner that the right answer would show up. – user5017397 Jul 22 '15 at 16:42
  • Instead of initializing `listofnums` to an empty list, why not just initialize it to the results of the list comprehension statement you do 2 lines below? `listofnums = [float(i) for i in nums]`. That way, you don't have to worry about appending. – ILostMySpoon Jul 22 '15 at 16:43
  • That a better way of doing it, thank you. I got my idea from another online source – user5017397 Jul 22 '15 at 16:47

0 Answers0