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 trialAdam Cassano
4,702 Pointsive been working on this for the last 2 days; im sure the solution is easy but i guess im not understanding whats wrong.
i also went back in the video and could not find where he used a for loop anywhere. if someone can help me understand this better i would appreciate it.
number_list = list()
total = (num)
def add_list(num): # add_list([1, 2, 3]) should return 6
number_list.append(num)
print("The Total is, {}".format(total))
for num in number_list:
total = num + num
# summarize([1, 2, 3]) should return "The sum of [1, 2, 3] is 6."
# Note: both functions will only take *one* argument each.
2 Answers
Dan Johnson
40,533 PointsThe challenge is expecting two separate functions: add_list to sum all elements of the list, and summarize, to format a string to display the result.
For add_list you'll want to loop through the list like you did, but to update the total as you go along you'll want to add the current value of total to the current element the loop is on:
def add_list(number_list):
total = 0
for number in number_list:
total = total + number #This can be shortened to total += number
return total
For summarize, you'll want to use the string exactly as it is shown in the challenge:
def summarize(number_list):
return "The sum of {} is {}.".format(number_list, add_list(number_list))
You won't need to create a list or append any data to one, a list will be supplied when your code is being checked.
Kenneth Love
Treehouse Guest TeacherWe do for loops in this video, on the stage previous to the one this code challenge is in.
Silviu Cosma
1,756 PointsSilviu Cosma
1,756 PointsHello Adam.
To pass this challenge we have to create the list:
list = [1, 2, 3]
After you define the function add_list which will take as argument our list:
def add_list(list): return "The total is {}.".format(sum(list)
print add_list(list)
To be able to do the sum all the elements from the list you have to use the sum() method.
There is no need to apply the for loop.