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

Patrick Nieto
Patrick Nieto
3,032 Points

I am having trouble with task 1 in functions.py. I am not sure how to correctly write the function in order to return 6.

What am I doing wrong here?

I don't understand what I should be calling the items in the list? should I be referring to them as num? Also, I have a feeling the argument sum is incorrectly used

functions.py
num_list = []

def add_list(sum):
  for num in num_list:
     sum = sum + num
  print(sum)





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

2 Answers

Dan Johnson
Dan Johnson
40,532 Points

You have the right idea on how to sum the list, but you're actually being passed in the list of numbers instead of a starting sum (if you were wondering why sum was highlighted, it's because it's the name of a built-in function). So here's an outline:

# Expect a list of numbers to be passed in (you can use a different name if you'd prefer).
def add_list(numbers):
  # Create a variable local to the function for the sum, starting at 0
  # Loop through and add to the total sum like you did before
  # Return the sum
Patrick Nieto
Patrick Nieto
3,032 Points

Thank you! That outline really helped!

Charlie Thomas
Charlie Thomas
40,856 Points

Hi! First off your argument should the list of numbers not sum since the function is using the list of numbers. Then inside your function make sure you set sum to 0 before your for loop. Finally, you need to return sum not print it. Your code should look similar to mine. If you want me to try and explain anything better - I'm not great at explaining stuff - comment below and I'll try.

def add_list(num_list):
  sum = 0
  for num in num_list:
    sum += num
  return sum