15/18 Why do i have to use range(len(something)) for the code to work


#1

why does this work

n = [3, 5, 7]

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

and this not - it returns index out of rnage error, but why

n = [3, 5, 7]

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

#2

Why not comment out the assignment inside the loop and print the value of i instead. It would probably be an eye opener :wink:


#3

i don't really get what you mean, could you perhaps do it and explain the wierd index error thing, thx


#4

Doing something like this and calling the function is one of the easiest ways to debug your code. You know that something is wrong with the index you are trying to access. The error message probably even say where in the code the error occurs. So simply check out what indexes you actually are trying to access:

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

If you run that you'll see what 'i' in this case and at the same time the indexes in 'numbers' you try to access.

You are probably misunderstanding what that type of for-loop does. It does not count 'i' up from 0 to something, instead it sets 'i' to each of the numbers stored in the list one after the other.

What you actually want to do when writing this kind of loop is something like this:

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

#5

I think it should be

n = [3, 5, 7]

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

or

n = [3, 5, 7]

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