Python3 for-loop even or odd
<p>Hi i got stuck in an exercise i have in school. and could use some help. </p>

<p>Create a for-loop that goes through the numbers:</p>

<pre><code>67,2,12,28,128,15,90,4,579,450
</code></pre>

<p>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.</p>

<p>Answer with the final result.</p>

<p>Here is my code so far.</p>

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

<p>ANSWER = a</p>

<p>when i run this program i get the answer:</p>

<pre><code>5.6 FAIL.
You said:
4 class 'int'&gt;
</code></pre>

<p>the correct answer should be <code>53</code> if initial value of <code>a</code> is <code>0</code>.  </p>

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

<p>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 <code>num % 2 == 0</code> and your indentation is not quite right. Try this instead:</p>

<pre><code>def listSum(l):
  ans = 0
  for num in l:
    if num % 2 == 0:
      ans += num
    else:
      ans -= num
  return ans
</code></pre>

<p>Note that you could do this in a single line:</p>

<pre><code>def listSum(l):
    return sum(i if i % 2 == 0 else -i for i in l)
</code></pre>

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

python python-3.x for-loop