Your own commands
def, parameters and return: naming a piece of work so the program reads like what it does.
Do this lesson in the simulatorforward and turn_right came with the robot. You can add your own.
Naming a piece of work
from bugbot import *
connect()
# a command of your own: one side of a shape
def side():
forward(50, distance=25)
turn_right(35, angle=90)
# now use it
side()
side()
stop()
def gives a name to a few lines. Nothing happens when Python reads the def; the lines run when you call the name with side().
Telling it how much
from bugbot import *
connect()
# how long the side is, is up to the caller
def side(cm):
forward(50, distance=cm)
turn_right(35, angle=90)
def square(cm):
for i in range(4):
side(cm)
square(20)
stop()
print("small square done")
cm is a parameter: a name that stands for whatever the caller passes in. square(20) draws a small one, square(40) a big one, and there is still only one description of a square in the program.
A function can also hand an answer back with return.
from bugbot import *
connect()
def gap_now():
# one reading, rounded to whole centimetres
return round(distance())
print("the gap is", gap_now(), "cm")
Why bother
Three reasons, and they are the same three in any language:
- the program says what it does:
square(30)reads better than twelve driving lines; - a fix happens in one place, not four;
- you can try a piece on its own, which is how you find what is wrong.
Task: draw an L
Write a function leg(cm) that drives that far forward and then turns right, and use it twice to walk the robot through both green squares: 40 cm, corner, 30 cm.
from bugbot import *
connect()
def leg(cm):
# drive, then turn
forward(50, distance=cm)
leg(40)
stop()
Challenges
- Add a
flash()function that blinks the light, and call it at each corner. - Give
lega second parameter for the speed:leg(40, 30). - Write
triangle(cm), and work out the angle inside the function rather than in your head.