''' write some code to print the items in a list, until the value 8 is encountered ''' data = [2, 6, 7, 8, 3, 8, 5, 9] print "Our list is",data print "Let's try the first way - it isn't correct!" for num in data: if num != 8: print num print "Now, let's improve the code" print "Reminder, our list is", data print "We should see the numbers 2, 4, 6, 3, 7 printed, but no others" i = 0 num = data[i] while num != 8: print num i = i + 1 num = data[i] print "We can make it shorter" i = 0 while data[i] != 8: print data[i] i = i + 1 print "What if the list is empty? we would get an error" data = [] print "Our list is now", data i = 0 while data[i] != 8: print data[i] i = i + 1 print "Comment out the 4 lines above, so we can go on this the code" print "We need to do error checking: make sure the list isn't empty" print "Let's try that now. Reminder, our list is", data if len(data) > 0: i = 0 while data[i] != 8: print data[i] i = i + 1 print "Ok, now our code can handle an empty list" print "" print "There is one case where our code is not yet right" print "What if the list does not contain an 8?" data = [10,11,12,13,14] print "We'll run our code now with data =", data if len(data) > 0: i = 0 while data[i] != 8: print data[i] i = i + 1 print "Comment out the above code, so we can move on" print "This version works in all cases:" if len(data) > 0: i = 0 while i < len(data) and data[i] != 8: print data[i] i = i + 1 print "But do we really need the if-statement, in our new version?" print "No!" print "Let's set data to be the empty list, and trace the code" data = [] i = 0 while i < len(data) and data[i] != 8: print data[i] i = i + 1