15. Iterating over a list in a function



Oops, try again. Your code looks a bit off. Check the console window for errors!

File "python", line 7
SyntaxError: 'return' outside function

Any help will be appreciated....

n = [3, 5, 7]

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


return should be under for I in range(len(list)):
result = 0
return result


Oh, the thing that made me put it their was because of the steps telling me to make the return = 0 before the For loop


I still get the error

File "python", line 5
for i in range(len(list)):
IndentationError: expected an indented block


Try putting your FOR function under TOTAL, it should do the trick


This is what I've done

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

and I'm getting the error

Traceback (most recent call last):
File "python", line 7, in
TypeError: 'function' object has no attribute 'getitem'


Actually you don't need to PRINT, you just need to return the correct answer!
And make sure that your RETURN is aligned with FOR.


Thank you!, so all I needed to do is not print total[n] ?, may I ask what this print total does? From my knowledge I see that it prints n = [3,5,7]


Yes it prints the "n", but i think that the problem is that the system does not recognize the command "print" as it is not given in instructions, I also tried to print "n" and got the same error!


Shouldn't the system recognize the word print always?

I tried it with print total and that does the trick----

function total at 0x7efe18557aa0>

prints that out on the console


Do u want me to help?


actually Never Mind I'll just go


Oh, sorry I was sleeping while you were asking :neutral_face:


well this is the code u need
n = [3, 5, 7]

def total(numbers):
result = 0
for x in range(len(numbers)):
result += numbers[x]
return result

print total(n)


what does the variable numbers with [x] represent or mean


Lets break the code down a little bit.

n = [3, 5, 7] # This is the list that will be iterated over

def total(numbers):
    result = 0 # This keeps track of the total amount

This is the more important part:

for x in range(len(numbers)):



will give you the amount of items in list n. In this case the amount of items would be 3.



(with 3 being the result from len) returns a list with numbers ranging from 0 to 2, so

[0, 1, 2]

Oversimplified, your statement says:

for x in [0,1,2]

The x is a variable for the index of the list you are iterating over. It can have any name. You can use this variable to access any item of the list. numbers[0] would output 3, etc.

    result += numbers[x] # add the number to the sum (numbers[0], numbers[1] and numbers[2])
    return result

Finally, we print the sum:

print total(n)


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