Numbers and names

Variables, arithmetic, and driving an exact distance instead of counting seconds.

0.2Python quick startRobot club10 min

Do this lesson in the simulator

Typing the same number in five places is how mistakes happen. Python lets you name a number once and use the name.

A name for a number

from bugbot import *
connect()

# a name, and what it stands for
speed = 60
seconds = 1.5

forward(speed)
wait(seconds)
stop()
print("drove at", speed, "for", seconds, "seconds")

Run this in the simulator

speed = 60 makes a variable. After that, speed means 60 everywhere in the program. Change the number once at the top and the whole program changes with it.

Names can hold the answer to a sum, too.

from bugbot import *
connect()

cm_per_second = 18
seconds = 2
print("that should be about", cm_per_second * seconds, "cm")

Run this in the simulator

Python does the usual arithmetic: +, -, * for times, / for divide.

Driving an exact distance

Counting seconds is guesswork. Every driving command takes a distance instead, in centimetres, and the robot works out the timing itself.

from bugbot import *
connect()

# 20 cm forward, then stop by itself
forward(50, distance=20)
print("position now", position())
# 15 cm to the right, still facing the same way
right(50, distance=15)
print("position now", position())
stop()

Run this in the simulator

distance=20 is a named argument: it says which 20 you mean. With a distance, the command waits until the robot has gone that far, so you do not need wait() after it.

It is still not perfect. The robot slides a little when it stops, and no two BugBots drift the same way. Getting from "about right" to "exact" is what Module 3 is for.

Task: two legs

Drive 40 cm forward, then 45 cm to the right, and stop in the green zone. Use distance= rather than counting seconds, and give the two distances names at the top.

from bugbot import *
connect()

first = 40
# your second distance here

forward(50, distance=first)
stop()

Challenges

  1. Do the same journey with the two legs the other way round. Does it end up in the same place?
  2. Make a variable slow = 25 and run the journey at that speed. Is it closer to the middle of the zone?
  3. Print the distance travelled in metres, not centimetres, using / 100.