13. product where is my mistake?



<Below this line, add a link to the EXACT exercise that you are stuck at.>
<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
returns 400 when it should return 100


def product(numbers):
result = numbers[0]
for number in numbers:
if number != 0:
result *= number
elif number == 0:
result == 0
return result

<do not remove the three backticks above>


As products go, zero is a factor that we would not wish to exclude. If there is a zero in the list, it should be allowed to apply, then break and return. The construct would be a variation on what you have (which is sort of overkill, btw)…

def product(numbers):
    result = 1    # force a non-zero unity preset
    for number in numbers:
        result *= number
        if result == 0:
    return result
print product([2,4,6,8,9])    # 3456
print product([2,4,0,6,8])    # 0


Hey! thanks for the quick response :slight_smile:
It appears that the bug was result = number[0], trying to figure out why but now it works !
I actually did exactly what you wrote which didn’t work as a result of what I wrote above which made me go insane and “overkill” lol


Yeah, when that happens it is a sure sign we can do better, but need to step away for a minute, or start over from scratch. What always throws me is working out the perfect algo (in my own mind) only to see a refactored form that puts it to shame. Never be hard on yourself for putting in an honest effort. How else would we be able to spot the jewels when we come across them?

def product(n)
    return reduce(lambda x, y: x * y, n)

z = [2,4,6,8,9]
print product(z)    # 3456