Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 864
knd15 Avatar asked Nov 28 '22 08:11

knd15


1 Answers

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)
like image 62
sampson-chen Avatar answered Dec 06 '22 10:12

sampson-chen