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

Nichelle Segar
Nichelle Segar
9,772 Points

Can I get an example of how to solve the challenge question?

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

# 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.

3 Answers

Here a for loop code i just made. Its pretty useless and there is a much 'efficient' way of doing it. Basically, the argument (num) is a list. The 'for loop' loops thought all the indexed item in the list and detects whether it holds the value '6'. It then returns True.

I think you can probably understand now how the exercise want you to design the code.

def find_six(num):
    '''([list of int]) -> bool
    Returns True iff it finds number 6.

    # Loops thought all the item in the list
    for each_num in num:
        # Returns True iff the item is equal to 6
        if (each_num == 6):
            return True

Sean T. Unwin
Sean T. Unwin
28,660 Points

Without knowing what you have tried so far, I will give you an answer in pseudo-code:

# Define add_list function which takes one argument for a list
  # Initialize variable for sum; set to 0
  # Loop through each number in the list
    # sum equals sum plus current number
  # Return the sum
William Ruiz
William Ruiz
10,027 Points

Here's my code, I hope it helps. I was definitely overthinking it. My biggest problem was converting the list to string, but remembering to use .format() helped.

def add_list(nums):
  for items in nums:
    items += items
  return items

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