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

Python Python Basics (Retired) Putting the "Fun" Back in "Function" Functions

I do not have any idea to pass Challenge Task 1 of stage5 - function.

I coded like this but it is wrong? why? how to solve it using by a 'for' loop and 1 arguments??

functions.py
# add_list([1, 2, 3]) should return 6
# summarize([1, 2, 3]) should return "The sum of [1, 2, 3] is 6."
# Note: both functions will only take *one* argument each.
function_list = [1, 2, 3]
def add_list():
  return function_list[0]+function_list[1]+function_list[2]

def summarize():
  print ("The sum of {} is {}.".format(function_list, add_list()))

This is the Task description.

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

1 Answer

Dan Johnson
Dan Johnson
40,533 Points

Since your function could be given a list of any length (the list in the comments is just an example), you can't use hard coded indexes to add everything up. That's why you use a for loop to pull out each element:

def add_list(numbers):
  # Running total. Start out at 0
  sum = 0

  # For every number in the list passed in
  #   Update the sum
  for number in numbers:
    sum += number

  return sum

Thank you for the comments. I coded as same and try it with 'add_list(6)'. However, I got an error as "TypeError: 'int' object is not iterable".

What am I wrong?

Dan Johnson
Dan Johnson
40,533 Points

6 is an int, so you can't iterate over it (it's not a container/collection of elements). You could do [6] if you wanted.

If this is for the challenge, you don't have to supply the arguments or anything. It'll check the function for you.

I made it! Thanks