Not true!?

Suppose we want to have Reeborg keep walking until he finds a beeper, and then turn himself off. An example of a starting position is below:

stop at beeper

One way to do this- in pseudocode- would be as follows:

If next to beeper,
... stop;
... keep moving.

Using what we have seen so far, we could translate this as:

if next_to_beeper():
This is only part of the solution as we have not told Reeborg to keep on repeating. Let's ignore this for now. Instead, consider the equivalent pseudocode formulation:

If not next to beeper,
...keep moving;

While we have reversed the order of "keep moving" and "stop", you should agree that the two ways are equivalent. The key point is the use of the negation "not" after the if in the second case. Python also allows us to negate some tests as follows:
if not next_to_beeper():

To transform this into a complete program, using what we have seen so far, we could need to define an instruction, and then have it repeated often enough to ensure that Reeborg can complete its task.

Your turn

Use the new Python keyword not and rewrite your jumping hurdle program.

Weeding and seeding time

It is spring time. Reeborg's father has seeded the garden for the fall harvest. 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 where two carrots (beepers) are, and reseed so that there is no places with no carrots. The final situation should look as follows:


Here's a suggestion for part of the code:

# 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():
    if not next_to_a_carrot():
        plant_carrot()      # replace missing seed
        if not next_to_a_carrot(): # oops!
            plant_carrot()  # we had removed the only one

Note that, in reality, it is not a good idea to remove seedlings and replant them right away!

previous If, else, if, else, .... - home - For a while next
../images/ Logo