"""indefinite-loops.py By Jadrian Miles, adapted from Jeff Ondich. A demonstration of various indefinite-loop constructs in Python. """ # An indefinite loop just keeps going and going while # some "continuation condition" is satisfied. This # condition is just an expression that evaluates to a # boolean value, True or False. As long as the # expression is True, the loop keeps executing. If # it's ever False, though, the loop stops. # There are lots of parts to this program. It may be # easier to work with if you comment out different # all the lines, and then uncomment only one section at # a time. You could also copy each section in turn into # a separate file, and run that little program instead. # As always, you can modify this program to inspect its # guts, too. Try using type() to check the types of # various things. ################################################################# # -- Run the loop below and see what happens. # -- What happens if you remove the "k = k - 1" line? # -- Can you make the loop count down by twos? # -- Can you make the loop count up by threes from 0 to 999? print '====== a while-loop counting down ======' k = 10 while k > 0: print k k = k - 1 print 'Boom.' print ################################################################# # Here's another while-loop. Compare it to the "for x in y" # loop from last time, where y was a string. print '====== a while-loop and a string ======' y = 'emus again' k = 0 while k < len(y): print y[k] k = k + 1 print ################################################################# # while-loops can do a lot of things other than simple # counting. What does this loop do? print '====== a more sophisticated while-loop and a string ======' y = 'emus again' k = 0 s = '' while k < len(y) and y[k].isalpha(): s = s + y[k] k = k + 1 print 'The resulting string is:', s print