Product ( code works alright but codeacademy shows error)


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/3?curriculum_id=4f89dab3d788890003000096


code works right but code academy says my code throws list out of range


def product(numbers):
    first_num=numbers[0]
    b=1
    c=0
    for item in numbers:
        c=first_num*numbers[b]
        b+=1
        c*=numbers[b]
        return c
        
print product([2,4,5])


#2

The line b+=1 is the problem.
There's 3 items in the list, and b is already set to 1. Everytime the loop runs it adds one to b, so by the third loop it's set too high as the maximum index is 2.


#3

I have removed that line of code and is still not working


#4

First you have to take care about your indentations! Think about your loop, what is happening when?

How does your code look like and what, does it give out now?

I think your problem is your for loop:

    for item in numbers:
        c=first_num*numbers[b]
        b+=1
        c*=numbers[b]

For every item in your list your loop calculates first_num*number[b] and store the result in c.
You said you removed b += 1, so I will ignore that.
Afterwards you multiply c with numbers[b] and store that one again in c. So let's go through your code for your example [2, 4, 5]

first_num will be set to numbers[0] which is 2

b=1
c=0

for item (the first one is 2) in numbers:
numbers[b] is 4, since b is 1
first_num (we set it to 2)* numbers[b] = 2*4, which is 8 and store that in c.
Now take c (8) times numbers[b] (still 4) store it again in c (32).
The loops first run is done. Now we take the second item which is 4 and do the same calculations. Remember we don't change first_num (2) ....
and so on. So there are some mistakes in you algorithm.
go through it and think about every single step.

Don't hesitate to ask if you need further help.
Kiluahh


#5

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