im trying to take this list that only takes integers and take the sum of it. the error im getting is (
can't multiply sequence by non-int of type 'float') from:
print (float(sum(bottles*.1)))
Code:
bottles = []
while True:
option = str(input('would you like to contiune? yes or quit '))
if option == 'yes':
bottles = [float(input("enter a number: ")) for _ in range(7)]
#i can't multiply sequence by non-int of type 'float'
print (float(sum(bottles*.1)))
if option == 'quit':
quit("you get no payment")
CodePudding user response:
You can't multiply a list by a float (you can multiply by an integer, but that just repeats the list, it doesn't multiply the numbers in the list). Calculate the sum first, then multiply that. It's equivalent by the distributive property of multiplication over addition (and you'll probably get a more accurate result because there are fewer opportunities for floating-point round-off errors).
print(sum(bottles) * .1)
CodePudding user response:
Try multiplying each value in the list by 0.1 using list comprehension and then print the sum of the new values, insead. For example:
bottles = []
while True:
option = str(input('would you like to contiune? yes or quit '))
if option == 'yes':
bottles = [float(input("enter a number: ")) for _ in range(7)]
# Multiply each value in bottle by 0.1 & print the sum
print(sum([(b*0.1) for b in bottles]))
if option == 'quit':
quit("you get no payment")
Brackets can be removed, for earlier versions of python, of course:
print sum([(b*0.1) for b in bottles])