0

That’s odd

In the That’s odd challenge, a list of numbers is generated, and the coder has to come up with a code to find the sum of all the even numbers on that list eg: [5, 4, 6, 1, 1, 8, 2] (input) Output: 20 It seemed easy to me at first, but I have been struggling with it for a little while now and not making progress. Here is my code so far: x = int(input()) num = 0 for i in range(x): y = int(input()) if (y%2) ==0: num += i print(num) Insight as to what I am doing wrong would be appreciated.

9th Nov 2021, 1:11 AM
MajesticPlatypus
MajesticPlatypus - avatar
3 Answers
+ 2
MajesticPlatypus In your example num was to be the final result as my s does here .. When you input your y you then went to condition fine but if condition met you added i to num verses y to num So your end result was based on loop number instead of new value given in y. in my example pulling from an array # array n = [1,2,3,4,5,6,7,8,9] # sum s=0 # digits in array for d in n: # if digits divisible by 2 equals zero if (d%2 == 0): # if condition met add digit to sum s += d # result print(s)
9th Nov 2021, 1:41 AM
BroFar
BroFar - avatar
+ 1
MajesticPlatypus if you know how many inputs you plan to use and are not using an array then do something like this .. In the following example I am saying 10 inputs needed for this problem s=0 # digits to be input range(?) for i in range(10): d = int(input()) # if digits divisible by 2 equals zero if (d%2 == 0): # if condition met add digit to sum s += d # result print(s)
10th Nov 2021, 12:39 AM
BroFar
BroFar - avatar
0
I changed my code to: x = [] s = 0 for i in x: if i % 2 == 0: s += i print(s) Which I thought might work, although the ouput was always 0. Since there are a few different lists in the challenge to compute, I think I have to take the generated list as input. If this is the case, how do I do so?
10th Nov 2021, 12:03 AM
MajesticPlatypus
MajesticPlatypus - avatar