If, else, if, else, if, else, ...

The previous hurdles exercise (you did try it, didn't you?) required to write an if/else within another one, all this because we wanted to give three choices to Reeborg: finish, move or jump. You may have noticed that this forced us to indent the code further and further. Imagine what would happen if we wanted to give Reeborg 10 mutually exclusive choices; the resulting code would become hard to read. To help us in such situations, Guido van Rossum, the creator of Python, has chosen a keyword that represents the combination of an else statement followed by an if clause. That keyword is elif, which we can think of as an abbreviation for else if. With this new keyword, the above code can be written as:

def move_jump_or_finish():
    if next_to_beeper():
        turn_off()
    elif front_is_clear():
        move()
    else:
        jump_one_hurdle()

We can now better see, as they are indented the same way, that there are three possible choices. The else condition is executed only if all the previous conditions are false, so there is no condition associated with it. If we have more than three choices, all we need to do is add other elif statements

def move_jump_or_finish():
    if next_to_beeper():
        turn_off()
    elif front_is_clear():
        move()
    elif right_is_clear(): # always false
        pass 
    else:
        jump_one_hurdle()

As Reeborg follows the bottom wall, right_is_clear() is always false, so the pass instruction (Python's equivalent of "do nothing") is always ignored. Note that if we had used left_is_clear() instead, Reeborg would have gotten stuck forever as soon as it had reached the first hurdle. Try it for yourself!

Your turn

Try to write a program using if, elif, else that works properly with the previous two hurdles courses as well as with the following (in file hurdles3.wld):

hurdles start
previous Listen to me ... or else .... - home - Not true!? next
../images/SourceForge.net Logo