The Station RemembersOnboard handbook

How loops work

Remember writing two go_forward() calls to reach the window? Each moved the robot one tile. With a loop you can write the step command once and run it several times in a row.

Which lines repeat?

A line starting with for or while ends with a colon. Start the lines underneath it with four spaces. Each time through the loop, Python runs those indented lines from top to bottom. Go back to the previous indent to write a command that runs after the loop.

Try it line by line

The robot is facing down the track. Watch for the line that turns its wheels. Then try the other loop and compare.

Loop type

for takes the next number from range and stores it in step. For each number, the indented line go_forward() runs once. In this example, range(3) gives 0, 1 and 2.

    Go back to The Long Gallery. If the robot needs to turn toward the door, put the turn before the loop at the left margin. The turn runs once, and the step inside the loop repeats. How many steps will it take to reach the first marker?