Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
MUZ140070 Nyasha L. Mupoperi
4,070 Pointspython code challenge task 1 of step 5
Make a function named add_list that takes a list. The function should then add all of the items in the list together and return the total. Assume the list contains only numbers. You'll probably want to use a for loop. You will not need to use input().
2 Answers
Vittorio Somaschini
33,371 PointsHello!
First we need to define the function that takes a list: def add_list(iterable)
After that we need to loop through all the numbers of the list and sums all the value, starting with the value of 0, so total = 0
The loop should look similar to this below: for item in iterable: total += item
This means that for all the elements inside the list, the loop adds the relative value to the toal, so when it finds 1 the total is 0+1 + 1, when it finds 2 the total becomes 1+2 = 3, when it finds 3 the total gets 3+3 = 6 and so on..
At the end we need to return the total, Here is my full code for it:
def add_list(iterable):
total = 0
for item in iterable:
total += item
return total
Vittorio
MUZ140070 Nyasha L. Mupoperi
4,070 Pointsthanks vittorio but this is the error message i am getting. Bummer! IndentationError: total += item
Vittorio Somaschini
33,371 PointsYou need to follow the indentation precisely. Does indentation in your your code appear exactly like the one I have written at the bottom of my answer?
Please paste your code
Kenneth Love
Treehouse Guest TeacherHowever much you indented your code inside of your function (the lines that are below the line that starts with def) is how much you need to indent the code inside if your for loop.