Doing it again

for and while, indentation, and a square drawn with four lines instead of twelve.

0.3Python quick startRobot club12 min

Do this lesson in the simulator

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

Run this in the simulator

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

Run this in the simulator

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

Run this in the simulator

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

  1. Make the square go anticlockwise with turn_left.
  2. Flash the light: for loop, led("red"), wait(0.2), led("off"), wait(0.2).
  3. Drive a triangle. What angle does each corner need?