Python Forum

Full Version: My function won't return the sum unless the last paramater is an odd number.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, I'm trying to return the summation of all even numbers, but the function won't return anything unless the parameter "y" is an odd number.
def sumOfEvens(x,y):
    total = 0

    while x <= y:

        if (x % 2 == 0):
            total = (total + x)
            
        elif (x == y):
            return total

        x = (x + 1)
            

I fixed it by removing the elif statment.
def sumOfEvens(x,y):
    total = 0

    while x <= y:

        if (x % 2 == 0):
            total = (total + x)
            
        x = (x + 1)

    return total
            
You know, a for loop would be much better in that situation:

def sum_evens(x, y):
    total = 0
    for z in range(x, y + 1):
        if z % 2:
            total += z
    return total