For a while ...

When we want to repeat some instructions until a certain condition is satisfied, Python gives us a simpler way to write this using a new keyword: while. Let me show you first how this would look using pseudocode to rewrite an example we have seen before.

While not next to beeper,
... keep moving;
... stop.

You should agree that this expresses the same idea as before. Using Python code, here how we would actually write it:

while not next_to_a_beeper():
No more need to repeat. Try it!

Your turn

Use while and not to rewrite the jumping hurdle program so that you don't have to use an arbitrary number of repeating statements. In other words, the core of your program should look like the following:

while not next_to_a_beeper():
Make sure it works!

Weeding and seeding time

It is spring time again. Reeborg's father has seeded the garden for the fall harvest. Just like last time, in some places, two seeds have sprouted whereas in others none have. A typical situation is shown below (file: harvest4.wld).


Help Reeborg weed the garden, so that there are no places with two carrots (beepers), and reseed so that there are no places with none.

Here's a suggestion for part of the code using the new keyword while:

# introducing vocabulary related to the problem
next_to_a_carrot = next_to_a_beeper
plant_carrot = put_beeper
pick_carrot = pick_beeper

def one_carrot_only():
    while next_to_a_carrot():
        pick_carrot()      # pick them all!
    plant_carrot()         # replant only one!

This piece of code is quite a bit shorter than the previous one (three lines inside the definition instead of six). Furthermore, it can work even when more than two seeds have sprouted at the same spot! Try it!
Remember that, in reality, it is not a good idea to remove seedlings and replant them right away!

previous Not true!? - home - Amazing - part 1 next
../images/ Logo