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?
product = 2
for i in xs:
if i%2 == 0:
product *= i
You need to initialize
product = 1, for two reasons. One, simply put, you'll get the wrong answer.
evens_product() 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