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.)