famguy74 famguy74 - 2 months ago 6
Python Question

Python multiplying all even numbers in a list

I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?

def evens_product(xs):
product = 2
for i in xs:
if i%2 == 0:
product *= i
return product

else:
return (1)


Edit: Chepner's solution worked thank you to everyone who helped

Answer

You need to initialize product = 1, for two reasons. One, simply put, you'll get the wrong answer. evens_product([4]) should return 4, not 8. Two, it saves you from having to treat a list with no even numbers as a special case. If there are no even numbers, you never change the value of product and return it unchanged.

def evens_product(xs):
    product = 1
    for i in xs:
        if i%2 == 0:
            product *= i
    return product