Iterating Over A List In A Function


#1

I think I am failing to understand something. I keep getting the response "Oops try again. total([0,3,6]) returned 15 instead of 9"
Any help would be appreciated.

n = [3, 5, 7]

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


#2

If you format your code, it will be nice. Python is indentation sensitive and I will need to see yours. :slight_smile:

Be that as it may, I think you should be looping for i in numbers and not n.

You could make this:

result += i.

It doesn't mean that was wrong but it makes your code more compact.

Hope this helps! :slight_smile:


#3

It must have lost it's indentation when I pasted it, my mistake.

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


#4

So, it's resolved now? :slight_smile:


#5

Unfortunately not, I'm getting the same error message.


#6

The indentation wasn't just the issue.

See suggestion code as recommended here:

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

Hope this helps! :slight_smile:


#7

Thanks for the help! I feel silly, in hindsight.


#8

:slight_smile:

Have fun coding!


#9

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