Doing it again
for and while, indentation, and a square drawn with four lines instead of twelve.
Do this lesson in the simulatorFour sides of a square, one line of Python each, is twelve lines that all say the same thing. A loop says it 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.
Run it twice. The two squares are not identical, and the robot does not land exactly where it started. 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(), or the loop spins as fast as the computer can go and the robot never hears from you.
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?