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
Diego Murray
2,515 PointsTrouble understanding BASIC PYTHON code
Please help me understand what this code is doing, exactly. In addition what is a counter and, in general, what usually goes in parenthesis when defining a function?
def add_list(list_of_numbers):
counter = 0
for item in list_of_numbers:
counter + item
return counter
1 Answer
Gunhoo Yoon
5,027 Pointsdef add_list(list_of_numbers):
counter = 0
for item in list_of_numbers:
counter + item
return counter
I would probably change the name counter to result, total, sumup or something on that line because that seems more clear to me.
Here what above code will do.
Takes a list, assuming all items in the list is number.
Set the starting point to 0 in case of empty list. (counter variable)
Go through each item in the list.
Add each item to counter variable.
After iterating through all item in the list return the counter which in this case sum of all items in list.
If something is unclear let me know what you don't understand.
Diego Murray
2,515 PointsDiego Murray
2,515 PointsGunhoo Yoon, so counter is an interchangeable name? Could you please elaborate a bit on step 2. What do you mean by starting point?
Gunhoo Yoon
5,027 PointsGunhoo Yoon
5,027 Pointscounter is just a variable name that holds initially holds 0. Variable name can be anything as long as it doesn't collide with reserved words and follows naming convention.