knd15 - 1 year ago 133
Python Question

# Sum of even integers from a to b in Python

This is my code:

``````def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += [i]
return count
``````

An example I put was print(sum_even(3,7)) and the output is 0. I cannot figure out what is wrong.

Your indentation is off, it should be:

``````def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += i
return count
``````

so that `return count` doesn't get scoped to your for loop (in which case it would return on the 1st iteration, causing it to return 0)

(And change `[i]` to `i`)

NOTE: another problem - you should be careful about using `range`:

``````>>> range(3,7)
[3, 4, 5, 6]
``````

so if you were to do calls to:

• `sum_even(3,7)`
• `sum_even(3,8)`

right now, they would both output `10`, which is incorrect for sum of even integers between 3 and 8, inclusive.

What you really want is probably this instead:

``````def sum_even(a, b):
return sum(i for i in range(a, b + 1) if i % 2 == 0)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download