Jed Rembold & Fred Agbo
January 17, 2025
Whenever a loop ends, you just return to the same indentation level as when that loop began
For loops inside other loops then, this means that the “inner-most” loop runs from start to finish for every step of the outer loop
while front_is_clear():
move()
while not_facing_north():
turn_left()
turn_left()
put_beeper()
Karel starts as shown to the right with 20 beepers in its bag. After executing the commands below, how many beepers are left in the bag upon the conclusion of the program?
while left_is_clear():
while front_is_clear():
move()
if no_beepers_present():
put_beeper()
turn_left()
Sometimes we know the number of times we want to loop
In these circumstances, the iterative statement called a for loop is best used
Syntax looks like:
for i in range(desired_count):
# statements to be repeated
desired_count
is an integer
indicating the number of times you want the loop to repeati
is a name that we will later make
more general, but for now you can always leave it as an
i
for
youimport karel
def main():
"""Draw a 4x4 square in the world."""
position()
draw_box()
def position():
"""Move to starting corner of box."""
move()
move()
turn_left()
move()
move()
turn_right()
def turn_right():
"""Turns Karel 90 deg to the right."""
turn_left()
turn_left()
turn_left()
def draw_box():
"""Draws a box with 4 equal sides in a CCW direction."""
for i in range(4):
draw_6_line()
turn_left()
def draw_6_line():
"""Draws a straight line of 6 beepers, if space."""
for i in range(5):
if no_beepers_present():
put_beeper()
if front_is_clear():
move()
if no_beepers_present(): # Last beeper to make 6
put_beeper()
move()
turn_left()
pick_beeper()
put_beeper()
front_is_clear()
Group code into bundles
def function_name():
# Code to be grouped
Run certain code blocks only if a condition is true
if condition_test:
# Code if answer yes
else:
# Code if answer no
while
loop: repeat code block as long
as condition is true
while condition_test:
# Code to repeat
for
loop: repeat set number of
times
for i in range(desired_count):
# Code to repeat
while no_beepers_present():
# if opening on right, we follow
if right_is_clear():
turn_right()
move()
else:
# go forward if possible or turn
if front_is_clear():
move()
else:
turn_left()
A good problem decomposition should mean:
import karel
def main():
# Here is our general solution with higher level of decomposition
for i in range(4):
find_next_tree()
remove_leaves()
def find_next_tree():
# the codes to find next tree
while front_is_clear():
move()
def remove_leaves():# codes to remove leaves
move_up()
deleaf()
move_down()
def move_up(): # to move karel up the tree
turn_left()
while right_is_blocked():
move()
def deleaf(): # function to deleaf
pick_beeper()
for i in range(3):
move()
pick_beeper()
turn_right()
turn_left()
def move_down(): # to move karel downward
while front_is_clear():
move()
turn_left()