Take Out the Trash

Tutorial

The do instruction lets Guido do an action more than once, but it has a limitation: you must know in advance how many times the action should be executed. If you are at an intersection and you need to pick up several beepers there but you don't know how many there are, you cannot use a do statement. The while statement can work in this situation.

The general format of the while instruction is

while test-condition-is-true:
    action

where test-condition-is-true is some conditional that evaluates to either true or false, and action is either a single command (like move;) or a sequence of commands in a block. As long as the tested condition is true, the action will be performed. Thus while is similar to do except that where do specifies a number of times to execute an instruction, while specifies a test condition. As long as the test condition is true, the instructions will be executed over and over.

For example, to pick up a stack of beepers you could write

while next_to_a_beeper:
    pickbeeper

This says that as long as there are beepers at this intersection, pick one up and check again. The result will be that there won't be any beepers at the current intersection. They will all be in Guido's beeper bag.

Writing a while loop is tricky; there are many details to get right. The general steps are

  1. Identify the condition that must be true when Guido is finished with the loop.
  2. Set up your while loop with the test being the opposite condition than the one that should finish it:
        while opposite condition:
            ...statements here...
      
  3. Make sure any setup code is complete before starting the loop so you start in a known condition. If conditions are specified, they are called preconditions.
  4. Make sure each pass through the loop makes progress towards completing the loop.
  5. Make sure the test for the loop eventually becomes false so you can get out.
  6. Write code for any cleanup work that needs to be done after executing the loop. When exiting the loop, of postconditions are specified, they will have been met if the preconditions were met when the loop was entered.

Watch out for infinite loops, that is, loops that never terminate.

Your Turn

It's Monday morning, again. Before he goes to school, Guido has to take out the trash. He's not sure how many bags of trash there are (represented by beepers), but he knows they are in the corner of the room as shown in this world view:

Step 12 image

He needs to pick up all the trash and put it in the dumpster in one trip. Use one or more while statements to instruct Guido to take out the trash. After depositing the trash, have Guido step back to see that the trash is properly in the dumpster.

Previous | Index | Next

Valid XHTML 1.1!   sourceforge.net   Valid CSS!

Copyright © 2003 Roger Frank.