Reeborg lives in Canada where it not only can rain or be sunny, but snow can also be falling ... usually not all three at the same time ... but it does happen... Let’s suppose that only one of those can happen. Then, Reeborg could be faced with the following choices:
if it_rains(): play_indoors() elif it_snows(): go_skiing() else: go_swimming() # assuming it is warm!
Notice the use of elif (which means “else if”) for choice 2. If we took into account other possible weather phenomena, like hail, thunder, fog, drizzle, etc., we could add other choices using additional elif: ... code blocks.
Here is a graphical representation of the choices that Reeborg faces:
A series of if/elif/ ... /else statements is equivalent to inserting the first code block that evaluates to True. Thus:
if False: do_1() elif True: do_2() elif True: do_3() else: do_4()
is equivalent to:
if False: do_1() elif False: do_2() elif False: do_3() else: do_4()
is equivalent to:
Just two lessons ago, you wrote a program that worked for worlds Hurdles 1 and Hurdles 2 but not for Hurdles 3. The reason it was not working for Hurdles 3 is that it was written with the assumption that the hurdles are evenly spaced. Let’s use our new condition front_is_clear() and keyword elif to change that.
Here’s a new program that should work for the world we mentioned above, provided you fill in the missing pieces correctly.
def jump_over_hurdle(): # suitable definition def run_jump_or_finish (): if at_goal(): # something elif front_is_clear(): # something else: # something repeat 42: run_jump_or_finish()
Note the structure of the if/elif/else statements; as is mentioned above, you should see that it gives three independent choices: only one of them will be executed.
Write such a program and make sure it works.
Could this program work without changing anything for world Hurdles 4? ... Have a look and you will likely conclude that the answer is no. You might want to try it just to be sure. It will take a little while until we are ready to write a program that can make Reeborg race Hurdles 4 as well as the other three.