Functions |
To teach Reeborg new functions (instructions) we define these new functions in terms of functions that Reeborg already knows or has learned. In a sense, user-defined functions allow us to create a dictionary consisting of new words that Reeborg can recognize. Like in a dictionary, these new words are accompanied by a definition of the new function. To illustrate how this is done, let us see what a user-defined turn_right() function definition looks like:
def turn_right(): turn_left() turn_left() turn_left()If we insert this definition in a Reeborg program, we can use the turn_right() instruction in directing Reeborg what to do. In other words, we have now taught Reeborg to turn right by executing three left turns. Note that turn_right() for Reeborg means exactly what the instructions indented after the def heading line say. The fact that turn_right has somewhat of a meaning in the English language is of no concern to Reeborg. We could have defined:
def self_destruct(): turn_left() turn_left() turn_left()If Reeborg was asked to execute the self_destruct() instruction he would of course not explode or destroy himself, but rather would make three left turns.
To indent instructions in a Python program, space characters (i.e., blanks) should be used, not tabs. In Python, 4 blanks are usually used to indent statements.
IDENTIFIERS: The name of a function is called an identifier. An identifier consists of the following characters: A-Z, a-z, 0-9, and the underscore. The identifier cannot contain any blanks and must begin with an alphabetic letter. (Actually, it can begin with an underscore, but there are circumstances where this can cause problems so it is best not to do so.)
Reeborg is supposed to climb stairs and pick up the beepers on each step. When he is done, he should be standing on the top step, facing East.
|
# A Stair Cleaning Program def main(): climb_a_step() pick_beeper() climb_a_step() pick_beeper() climb_a_step() pick_beeper() turn_off() # Climb on to next step def climb_a_step(): turn_left() move() turn_right() move() # Pivot Reeborg 90 degrees to right def turn_right(): turn_left() turn_left() turn_left() # Invoke main() main() |
Example:
During the summer Reeborg works as a field laborer. His task is to harvest the field of beepers. He can relax and turn off as soon as he has harvested all beepers and stepped out of the field. |
Program 1 | Program 2 |
move() pick_beeper() move() pick_beeper() ... turn_left() move() turn_left() pick_beeper() move() ... turn_left() turn_left() turn_left() move() turn_left() turn_left() turn_left() pick_beeper() move() ... turn_off() |
move() harvest_2_rows() position_for_next_harvest() harvest_2_rows() position_for_next_harvest() harvest_2_rows() move() turn_off() |
Program 1 Critique | Program 2 Critique |