Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

reza sajadian
reza sajadian
718 Points

problem with my Python code

I'm stuck in some quiz, and nobody helps me out! can anybody take a look at my code to see why it doesn't work?

the problem:

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

My code:

total = int()
list = [1, 2, 3]

def summarize(item):
  total = (total+list[item])

def add_list(list):
  for item in list:
    summarize(item)
    return(total)

add_list(list)

2 Answers

Hi Reza,

The first part of this, the add_list method could look something like:

def add_list(lst):
    count = 0
    for item in lst:
        count = count + item
    return count

I hope that helps.

Steve.

The next part could be:

def summarize(lst)
  return ("The sum of {} is {}.".format(lst,add_list(lst)))

That uses string interpolation to insert the variables at each {} marker. The two variables are the formatted list and the result of passing that list to the original add_list method.

reza sajadian
reza sajadian
718 Points

yeah it worked, Thanks so much. But I had tried some parts the same before, and it didn't work that way. can you explain to me what was the big difference or obvious mistake I made?

I'm not big on criticising other people's code - I'm not sure that's constructive.

However, you could loook over what you did inside your for loop - did that add up the elements in the array? You've passed the addition out to another method called summarize that uses the variable total that isn't declared. It then accesses the list with the vale of the index as the element. Thankfully, our array/list is [1, 2, 3] so that's not going to cause huge problems (are lists zero-indexed?). If the first element was 150, trying to access list[150] would throw an out-of-bounds exception.