Jed Rembold
September 3, 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 single step of the outer loop
What does the below chunk of code accomplish?
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()
Karel starts as shown to the right. At which beeper do they end up when the below sequence of commands finishes?
while no_beepers_present():
while front_is_clear():
move()
if beepers_present():
turn_left()
else:
turn_right()
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|||):
|||commands to be repeated desired count times|||
|||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
ifor 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|||A good problem decomposition should mean: