Two loops for a spiral
Eight tiles down, turn, seven left, turn, six up. How can you write one program for the whole spiral?
What do you count at each corner? What do you count on each tile?
The outer for loop picks the length of one whole segment. When n = 8 the expression range(n, 0, -1) gives 8, 7, 6, 5, 4, 3, 2, 1. The first number is n. A step of -1 makes each length one tile shorter than the last. The range stops before zero.
In this program, step holds the chosen length. At the start of each segment, i = step copies that length into a separate counter. The inner while loop moves the robot while i is greater than zero. After each step, i goes down by one, and step stays the same until the next segment.
Trace the program line by line
Watch the two numbers in the log. Can you predict the pair that comes immediately after 8 1? Select “Run to the next turn” to finish the current segment.
n = 8for step in range(n, 0, -1):i = stepwhile i > 0:print(step, i)go_forward()i -= 1turn_right()
step = —i = —Output from print(step, i)
Why does the robot turn only once?
Indent print(step, i), go_forward() and i -= 1 by eight spaces. All three lines belong to the while loop. The program prints before it moves, so the second number counts the tiles still ahead, including the very next one.
Indent turn_right() by four spaces, so it lines up with while. When i reaches zero, the inner loop ends. The robot turns once, and the outer for loop picks the next length. At the end, the robot turns in place and stays in the center.
Go back to The Spiral and compare the first two segments of your program with this example.