Code in Place_Lesson 2_slides
Code in Place_Lesson 2_slides
def main():
go_to_moon()
def go_to_moon():
build_spaceship()
# a few more steps
def build_spaceship():
# todo
put_beeper()
def main():
# repeats the body 99 times
for i in range(99):
# the “body”
put_beeper()
def main():
# while condition holds runs body
# checks condition after body completes
while front_is_clear():
move()
def main():
# If the condition holds, runs body
if front_is_clear():
move()
def main():
# If the condition holds,
if beepers_present():
# do this
pick_beeper()
else :
# otherwise, do this
put_beeper()
We are going to
need to decompose
the task
Muhammed ibn
Musa Al Kwarizmi
Piech and Sahami, CS106A, Stanford University
Piech and Sahami, CS106A, Stanford University
Pro Tips
A good function should do ”one conceptual thing”
Well commented
Lather,
Rinse,
Repeat
def turn_to_wall():
while left_is_clear():
turn_left()
def turn_to_wall():
while left_is_clear():
turn_left()
def turn_to_wall():
while left_is_clear():
turn_left()
def turn_to_wall():
while left_is_clear():
turn_left()
What do you
def climb_mountain: assume here?
while front_is_clear():
# step up
move()
turn_left()
move()
8 . . . . . . . .
7 . . . . . . . .
6 . . . . . . . .
5 . . . . . . . .
4 . . . . . . . .
3 . . . . . . . .
2 . . . . . . . .
1 . . . . . . . .
2 . . . . . . . .
• How should we approach
this tricky problem? 1 . . . . . . . .
1 2 3 4 5 6 7 8
1
. . . . . . . .
1
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
. . . . . . . . . . . . . . . .
8
. . . . . . . .
8
. . . . . . . .
7
. . . . . . . .
7
. . . . . . . .
6
. . . . . . . . 6
. . . . . . . .
5
. . . . . . . . 5
. . . . . . . .
4
. . . . . . . . 4
. . . . . . . .
3
. . . . . . . . 3
. . . . . . . .
2
1
. . . . . . . . 2
1
. . . . . . . .
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8