Product


#1



def product(numbers):
    count=0
    total=product[0]
    while count<len(product):
        total*=product[count+1]
        count+=1
    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!


#2

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


#3

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.


#4

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

def product(numbers):
    count=0
    total=numbers[0]
    while count<len(numbers):
        total*=numbers[count+1]
        count+=1
    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

#5

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


#6

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:


#7

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


#8

That works, thanks a lot!


#9

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