oliver Bergman oliver Bergman - 1 year ago 86
Python Question

Python3 for-loop even or odd

Hi i got stuck in an exercise i have in school. and could use some help.

Create a for-loop that goes through the numbers:


If the current number is even, you should add it to a variable and if the
current number is odd, you should subtract it from the variable.

Answer with the final result.

Here is my code so far.

def listnum(a):
for num in [67, 2, 12, 28, 128, 15, 90, 4, 579, 450]:
if (num%2):
a = a + num
a = a - num
return a


when i run this program i get the answer:

5.6 FAIL.
You said:
4 class 'int'>

the correct answer should be
if initial value of

can any one help me and tell what im doing wrong?
or maybe point me in the right direction.
thank you!

Answer Source

I think it would make more sense if your function input is the list and not the return value. Also (as others have noted) you need num % 2 == 0, and your indentation is not quite right. Try this instead:

def listSum(l):
  ans = 0
  for num in l:
    if num % 2 == 0:
      ans += num
      ans -= num
  return ans

Note that you could do this in a single line:

def listSum(l):
    return sum(i if i % 2 == 0 else -i for i in l)

print(listSum([67, 2, 12, 28, 128, 15, 90, 4, 579, 450])) prints 53 in both cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download