Doing it again
for and while, indentation, and a square drawn with three lines instead of eight.
Do this lesson in the simulatorPrint it: worksheet (PDF) · answers (PDF) · as a web page
Four sides of a square, each a drive and a turn, is eight lines that say the same two things four times. A loop says them once.
A loop that counts
from bugbot import *
connect()
# do everything indented below this line four times
for i in range(4):
print("this is time number", i)
range(4) counts 0, 1, 2, 3, so the indented lines run four times. The indentation is not decoration: it is how Python knows what is inside the loop and what comes after it.
A square
from bugbot import *
connect()
for i in range(4):
# one side
forward(50, distance=25)
# the corner
turn_right(35, angle=90)
stop()
print("finished at", position(), "facing", heading())
turn_right(35, angle=90) spins the robot a quarter turn on the spot. heading() says which way it is facing in degrees: 0 is the way it started, 90 is a quarter turn to the right.
Look at the last line: it finished at about (-0.4, 0.2), facing 358 rather than 0. Four perfect corners would bring it back to exactly where it started, and the robot does not quite manage it. That is the drive, not your program.
A loop that keeps going
Sometimes you do not know how many times. while repeats while something is true.
from bugbot import *
connect()
led("blue")
start = clock()
# keep going until three seconds have passed
while clock() - start < 3:
forward(40)
# a short wait each time round, so the robot knows the program is still there
wait(0.1)
stop()
led("off")
clock() is the seconds since the program started. Inside a while loop that drives, always leave a small wait(). Without it the loop spins as fast as the computer can go, no time passes for the robot, and BugBot stops the program and asks for a wait(0.1) inside the loop.
Task: four corners
Drive a square: 30 cm a side, turning right at each corner, using a for loop. The four green squares are the corners it has to pass through.
from bugbot import *
connect()
for i in range(4):
# one side and one corner
forward(50, distance=30)
stop()
Challenges
- Make the square go anticlockwise with
turn_left. - Flash the light:
forloop,led("red"),wait(0.2),led("off"),wait(0.2). - Drive a triangle. What angle does each corner need?