def product(numbers):
    while count<len(product):
    return total
print product([4, 5, 5])

Practive Makes Perfect - Product

The object is just multiple every number in the list. Please help with point the error in the above code!


product is the function, numbers (the function parameter) contains the list.


Initialize total to 1.

Then, loop through the list of numbers, multiplying each number by the total and iteratively assigning the product to the total:

total = 1

for num in numbers:
    total *= num

Finally, return the total.


Thanks! You are right, that is a big mistake. Now here is what the code looks like:

def product(numbers):
    while count<len(numbers):
    return total
print product([4, 5, 5])

and the error code is:

Traceback (most recent call last):
  File "python", line 9, in <module>
  File "python", line 5, in product
IndexError: list index out of range


Thank you. That way definitely works! I am just wondering if there is any way we can keep while loop here.


Sure, there is.

Initialize a result variable to 1.
Initialize a count variable to 0.

While the count is less than the length of the list (function parameter), multiply the result by list[count] and iteratively assign the product to the result, and then increment count by 1.

Finally, return the result.

But, using while for looping through sequences is not Pythonic :slight_smile:


Change total=numbers[0] to total = 1.
Also, change total*=numbers[count+1] to total *= numbers[count]


That works, thanks a lot!


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