Iterating over a list in a function


#1

Hey guys, I'll be honest I no longer have much clue what I am really doing in my code anymore. Every time a new problem comes up I have to refer to the Q & A form. Mostly because the wording of the instructions can be very confusing for me. In this case I don't understand how to add each number to the result because I'm unfamiliar with how to actually do so.

n = [3, 5, 7]

def total(numbers):
    result = 0
    for n in numbers:
        result += n
        return result

Oops, try again. total([0, 3, 6]) returned 0 instead of 9

`


#2

hi @toxicxp ,
It seems that your return statement is not indented well.
Make sure its indented same level as your for loop.


#3

a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the function needs to end, so the loop will break

so, your loop breaks in its first iteration/loop

like @greentreemee says, place return outside your loop (indention) so your whole loop can run


#4

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