Repeatedly Executing Instructions |
for identifier in range(iteration-amount): <loop body statement(s)> |
Example | Explanation |
def turn_right(): for x in range(3): turn_left() |
The primitive instruction turn_left() is repeated three times, which is equivalent to a right turn. |
def harvest_a_row(): pick_beeper() for x in range(4): move() pick_beeper() |
Reeborg would pick a single beeper and then repeat the sequence
move() + pick_beeper() four times.
The new instruction would therefore in total execute
five pick_beeper() instructions and four move()'s.
|
Note that the statements in the loop bodys (that is, the block of statements to be repeated) must be indented and must be indented to the same level. Recall that 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.
for statements can be nested inside each other as in the following example:
def traverse_square(): for x in range(4): for x in range(2): move() turn_left() |
The while statement is made-to-order for this situation:
you can use it to tell Reeborg to repeat something while a certain predicate
is True; for example to pick up beepers while there any to pick up.
while predicate: <loop body statement(s)> |
For example, if we wish to instruct Reeborg to walk forward until he is in front of a wall, the logic for this is shown in the flowchart to the left and would be implemented with the Python code to the right:
while front_is_clear(): move() |
NOTE: If the predicate is initially False the
statement(s) in the loop body will not be executed at all.
For this reason, while loops are sometimes called
zero-or-more times loops.
Other Examples | Explanation |
def clear_corner_of_beepers(): while on_beeper(): pick_beeper() |
Reeborg would pick up all beepers on the current corner, regardless how many there are (if it is a finite number, at least). |
def face_north(): while not facing_north(): turn_left() |
Reeborg will turn left as often as necessary in order to be facing North at the end of executing this function. Note that if this function is invoked when Reeborg is already facing North, zero turn lefts will occur. Note also how much shorter this implementation of face_north() is compared to the implementation that used a series of three IF statements. |
def pick_beepers_to_wall(): while on_beeper(): pick_beeper() while front_is_clear(): move() while on_beeper(): pick_beeper() |
The logic of these nested while statements has Reeborg pick up all beepers between him and the wall ahead of him, including beepers on Reeborg's beginning street corner. Reeborg stops in front of the wall. |