Your own commands

def, parameters and return: naming a piece of work so the program reads like what it does.

0.5Python quick startRobot club12 min

Do this lesson in the simulator

forward 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()

Run this in the simulator

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")

Run this in the simulator

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")

Run this in the simulator

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

  1. Add a flash() function that blinks the light, and call it at each corner.
  2. Give leg a second parameter for the speed: leg(40, 30).
  3. Write triangle(cm), and work out the angle inside the function rather than in your head.