''' while.py Jeff Ondich, 26 September 2018 This sample program introduces the while-loop. ''' # Since there are a lot of pieces to this program, you # may want to use copy and paste to run just one piece # at a time while you investigate each kind of loop # structure. That's up to you. # 1. Run the loop below and see what happens. # 2. What happens if you remove the "k = k - 1" line? # 3. Can you make the loop count down by twos? # 4. 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('Lift-off.') print() # Here's another while-loop. Compare it to the for x in y # loop above 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() # Next: nested loops. That is, loops inside loops. # Try to predict what this loop will print. print('====== nested loops, first example ======') for j in range(4): for k in range(3): print(j, k) print() # This one's trickier. Can you predict it? Can # you explain why it does what it does? print('====== nested loops, trickier ======') for j in range(4): for k in range(j): print(j, k) print()