Getting Out of the Loop

In the last post, we explored Python lists and in Exercise #7 you were asked to sum the items in the list of numbers up to, but not including, the first even.  This turns out to be slightly more complicated than the other “traversing a list” exercises that we have completed.

Basically, to be efficient, we want to create a loop that stops when it hits an even number.  In class, we were presented with two possible solutions, which I will present here.

The first solution involves a while loop.  The advantage is that the while loop will be in charge of the decision to stop.  The disadvantage is that the programmer is in charge of keeping track of the position in the list.

# Write a program that will accept a list of numbers from the user and 
# displays the sum of all the elements up to, but not including the first 
# even number. (Stop when you hit an even.) Save the program with the 
# filename yourname-lists-7.py

l = raw_input('Please enter a list of numbers separated by commas: ').split(',')
l = map(int, l)

total = 0
p = 0 # postiton in the list l

while p < len(l) and l[p] % 2 != 0:
    total = total + l[p]
    p = p + 1

print('The sum up to the first even number is ' + str(total) + '.')

The second solution involves a for loop with a break statement.  The advantage of this solution is that the for statement keeps track of our position in the list.  The disadvantage is that we have to introduce an if block to make the decision to stop.

# Write a program that will accept a list of numbers from the user and 
# displays the sum of all the elements up to, but not including the first 
# even number. (Stop when you hit an even.) Save the program with the 
# filename yourname-lists-7.py

l = raw_input('Please enter a list of numbers separated by commas: ').split(',')
l = map(int, l)

total = 0

for stuff in l:
    if stuff %2 != 0:
        total = total + stuff
    else:
        break

print('The sum up to the first even number is ' + str(total) + '.')