15. Iterating over a list in a function


#1
n = [3, 5, 7]

def total(numbers):
    result=0
for i in range(len(numbers)):
    result = result +(numbers)
    return result

Notice the indentation has disappeared - all the result statements are indented. How do I paste a print screen? - standard method does not work

Can someone help having problems with the last line - return result. Get the result - “SyntaxError: ‘return’ outside function”. Have tried changing the indentation - and then get the error “unexpected indentation”.


#2

why is the for loop not nested inside your function?


#3

Hi @pennycox0,

Since your code is not formatted, we cannot see its indentation.

(EDIT (August 3, 2017): The user has now formatted the code); Thanks!

Make sure your entire for loop is indented, so that it is part of the total function.

Also make sure that the return statement is indented to a degree that makes it part of the function, but not part of the for loop.


#4

When I copied and pasted the code the indents disappeared. Tried to print screen my code but could not paste it. How can I paste a print screen?


#5

or you can use format to make your code show:

posting a screenshot is also possible

but i looked, even with the indent of your code the for loop is not nested inside the function


#6

Thanks - code is now formatted as on my screen


#7

Thanks for the formatting, @pennycox0.

See @stetim94’s reply here, regarding the for loop.

Also, reconsider this …

    result = result +(numbers)

#8

Believe my indentation is correct - have tried various different formats for the result = section - none of which have worked. Have tried result = result + i


#9

I have resolved it. Since the software was updated, a tab is no longer equal to 4 spaces. I re-did the spacing and changed result = result + numbers[i]. and it finally works.
thanks for your help


#10