HappyHands31 HappyHands31 - 8 days ago 4
Python Question

Function That Sums All Elements in List Up to But Not Including The First Even Number

I'm trying to write a python function that will sum up all of the elements in a list up to but not including the first even number. The function needs to pass the following tests:

from test import testEqual

testEqual(sum_of_initial_odds([1,3,1,4,3,8]), 5)
testEqual(sum_of_initial_odds([6,1,3,5,7]), 0)
testEqual(sum_of_initial_odds([1, -7, 10, 23]), -6)
testEqual(sum_of_initial_odds(range(1,555,2)), 76729)


I tried the following:

import random

lst = []
def sum_of_initial_odds(nums):
sum = 0
#test if element is odd number - if it's odd, add it to the previous integer
for i in lst:
if i % 2 != 0:
sum = sum + i
return sum
#test if element is even number - if it's even, don't include it and break code
else:
if i % 2 == 0:
break:


I'm currently getting a parse error:

ParseError: bad input on line 11


which is the line:

else:


How else can I write this code so that it adds the elements in a list, but doesn't include the first even number, without getting Parse errors?

Answer

You have a few problems:

  1. Indentations, which others have already mentioned
  2. You return sum the first time you hit an odd number; this is so not what you want.
  3. You ignore the input parameter nums and work with the empty global lst.
  4. Your lowest if is redundant: you already know you have an even number when you get here.

In general, stuff partial results into local variables; have a single return at the bottom of your routine.

import random

def sum_of_initial_odds(lst):
    sum = 0
#test if element is odd number - if it's odd, add it to the previous integer
    for i in lst:
        if i % 2 != 0:
            sum = sum + i
#test if element is even number - if it's even, don't include it and break code
        else: 
            break

    return sum

print sum_of_initial_odds([1,3,1,4,3,8]) == 5
print sum_of_initial_odds([6,1,3,5,7]) == 0
print sum_of_initial_odds([1, -7, 10, 23]) == -6
print sum_of_initial_odds(range(1,555,2)) == 76729

THe output from this is four True values.