Lesson 15


so after trying different things for half and hour, this works, but why does it work?

can someone please explain in laymens terms why this workes and cleared this section?

n = [3, 5, 7]
def total(numbers):
    result = 0
    for item in numbers:
       result += item
    return result
print total(n)


n = [3, 5, 7] #Random list for testing
def total(numbers): #Creates a function called total and has an input variable placeholder called numbers which can be replaced by a random list when you call the function
    result = 0 #Going to use this to add numbers to it. Needs to have a value first so 0.
    for item in numbers: #Goes through each item in the list you're going to input
       result += item #adds the item to result
    return result #returns the result and ends the function -> this does not print anything to the console
print total(n) #calls the function and prints result into the console with random list being inputted/replacing input placeholder variable, number

See comments. If there are any specific questions, feel free to ask.


things is, i put the print command to see the results displayed and the answer was 15.

I thought this program was interating the whole list, number by number, so would the output have been some thing like [4, 6, 8]

15 is the total of the original list added together.


Output should be one number which is the sum of the numbers in an inputted list.

You have n = [3, 5, 7] and you called it by doing print total(n) which will output 15 in the console.
If you did print total([4, 6, 8]) below it, you can see 18 in the console. Try it out.

It is interacting with the whole list in order to add the numbers inside them together. Like 3 gets added to result first, then 5, and then 7.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.