🚀 Alguni Start learning

Unit 3: Do It Again

One loop instead of four copies.

Unit 3 of 8 in Robotics coding for kids. Its 4 lessons are Four Times, Polygons, The Loop Counts and Lap of the Lab — below is everything each one explains, and a question or two from it to try.

Every program on this page was driven round the simulated room before it shipped, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

🔂 Four Times

Say it once, do it four times

A square was eight lines, and six of them were copies. for says the same thing in three:

for something in range(4): means "run the indented lines four times".

The indent is how Python knows which lines belong to the loop.

Python

for side in range(4):
    robot.forward(50)
    robot.right(90)

robot.say(robot.heading())

It prints

0.0

Try it yourself

How many times do the indented lines run in for side in range(4):?

  • 4
  • 3
  • 5
  • Until the robot bumps

Bolt starts at 100, 160 facing up. What does this print?

Python

for step in range(3):
    robot.forward(20)

robot.say(robot.y())

Answer them in the app

🔷 Polygons

One loop, any shape

The turn at each corner is always 360 divided by the number of corners. Put that in the loop and the same three lines draw anything.

Change the 6 to a 3 and it is a triangle. Change it to 12 and it is nearly a circle.

Python

sides = 6

for corner in range(sides):
    robot.forward(30)
    robot.right(360 / sides)

robot.say(robot.heading())

It prints

0.0

Try it yourself

What does this print?

Python

for corner in range(3):
    robot.right(72)

robot.say(robot.heading())

Answer it in the app

🌀 The Loop Counts

The loop knows which turn it is on

The name after for is not decoration. On the first pass it is 0, then 1, then 2 — so the robot can do something a little different each time.

Here every side is longer than the last, and the square unwinds into a spiral.

Python

for i in range(5):
    robot.forward(10 + i * 10)
    robot.right(90)

robot.say(robot.heading())

It prints

90.0

Try it yourself

What does this print?

Python

total = 0

for i in range(4):
    total = total + 10

robot.forward(total)
robot.say(robot.y())

In for i in range(3):, what is i on the very first pass?

  • 0
  • 1
  • 3
  • Nothing yet

Answer them in the app

🏆 Lap of the Lab

Try it yourself

Why write a loop instead of the same four lines four times?

  • Because changing the shape then means changing one number, not sixteen lines
  • Because loops make the robot drive faster
  • Because Python does not allow repeated lines
  • Because it uses less battery

Answer it in the app