sak
sak

Reputation: 123

How to sum even or odd numbers in a list given the condition odd or even?

So the problem is asking me to return the sum of even or odd elements in a list given the condition odd or even. So if the condition is odd, I have to return a list of all odd numbers. If the list is blank/the values do not match the condition, then return 0.

This is what I have so far:

l = [1,2,3,4,5,6]

def conditionalSum(value, condition):
    s = 0
    if condition == "even":
        for i in l:
            if i % 2 == 0:
                s += i
    elif condition == "odd":
        for i in l:
            if i % 2 !=0:
                s = s+ i
    else:
        return 0

When I try to run this, nothing comes up - not even an error! Any help is appreciated

Upvotes: 2

Views: 1811

Answers (2)

Necklondon
Necklondon

Reputation: 998

  1. you need to call the fonction: conditionalSum(l, "even") for instance
  2. you don't return any value for the 2 conditions "even" and "odd". Corrected code:
l = [1,2,3,4,5,6]

def conditionalSum(value, condition):
    s = 0
    if condition == "even":
        for i in value:
            if i % 2 == 0:
                s += i
    elif condition == "odd":
        for i in value:
            if i % 2 !=0:
                s += i
    return s

print(conditionalSum(l,"even"))
print(conditionalSum(l,"odd"))

Upvotes: 2

Vishal Singh
Vishal Singh

Reputation: 6234

your code can be modified to be more pythonic using a built-in sum function.

l = [1, 2, 3, 4, 5, 6]

def conditionalSum(value, condition):
    if condition == "even":
        return sum(i for i in l if i % 2 == 0)

    elif condition == "odd":
        return sum(i for i in l if i % 2 == 1)

    else:
        return 0

print(conditionalSum(value, "even"))

Output:

12

btw you have an unused variable value in your function conditionalSum

Upvotes: 4

Related Questions