Reputation: 9
I'm trying to do this question for this online coding course I'm part of, and one of the questions requires me to add together integers in a list. I've tried to find the answer (and visited a few other pages on this site), but I can't think of anything. Help please!
Here's my code so far:
total = 0
att = input("RSVPs: ")
att = att.split(",")
for i in att:
print(sum(iatt) for i in att)
Upvotes: 0
Views: 63
Reputation: 160377
Your error is caused because you provide sum with an integer value (iatt = int(i)
) when you should be providing it with the contents of the list which is split on ','
.
You have a couple of options for this. Either provide a comprehension to sum
and cast every element to an int
inside the comprehension:
print(sum(int(i) for i in att))
or, use a built-in like map
which pretty much does the same thing:
print(sum(map(int,att)))
in both cases, sum
expects something that can be iterated through and it handles the summing.
Of course, you could manually loop over the contents of att
, adding int(i)
to total
as you go:
for i in att:
total += int(i)
print(total)
Upvotes: 6