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 trialAndy Christie
1,361 PointsPlease can you tell m what's wrong with this python code
please can someone help me with this
# 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.
def add_list([1, 2, 3]):
result = 0
for items in li:
result += items
return result
def summarize(li):
return "The sum of {} is{}".format(add_list(), result)
1 Answer
Thomas Nelson
8,651 PointsHi Andy,
The first problem is that your add_list function is trying to work on an internal variable called "li", but "li" hasn't been declared anywhere. It would be better if your function took "li" as an input (as you do in summarize_list), and then declare your test case li = [1, 2, 3] when you call the function at the end. You could then do this:
def add_list(li):
result = 0
for item in li:
result += item
return result
The second problem is that your summarize_list function is trying to access a variable that does not exist in the global scope. The "result" variable is internal to the add_list function and so summarize_list can't access it as written. You need to store the output of add_list somewhere. You could do this either by adding a line like this one in the main part of your program (i.e. not inside a function),:
result = add_list(li)
or you could simply call the function in your summarize statement (see code below). Also, note that the function won't actually display the answer to the command line as it is written (it will return a string but not show it). I've modified your code to print upon call, rather than returning a value.
def summarize_list(li):
print("The sum of {} is {}.".format(li, add_list(li)))
At the end, define your test list and then call summarize_list.
li = [1, 2, 3]
summarize_list(li)
When you run functions.py now, you should see your summary.
I hope that's helpful!
Cheers, Tommy