HappyHands31 - 10 months ago 42

Python Question

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 Source

You have a few problems:

- Indentations, which others have already mentioned
- You return
**sum**the first time you hit an odd number; this is*so*not what you want. - You ignore the input parameter
**nums**and work with the empty global**lst**. - 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.