3.1.2. Iteration
When programming, iteration is another way of saying loop, and it means repeat a piece of code. This might be a specific number of times or until a condition is met.
Start with importing the turtle code and assigning the drawing function to a variable so you can write shorter code. Add a pen.forward(50) command to check you have written it properly then delete it before adding the loop code. If you get an error, read what line the error is on and see if you can spot the mistake.
import turtle
pen=turtle.Turtle()
pen.forward(50) # Delete this line after testing
Next, create a ‘for loop’ that will repeat the code a set number of times.
for i in range (0,4):
pen.forward(50)
pen.right(90)
Run the code and see what happens. It should draw a square.
Note
The colon at the end of the for loop is important. Do not forget it!
Note
Indentation of code inside the loop is important. Code inside a loop is four spaces in.
3.1.2.1. Next steps
Can you change the 90 in the pen.right(90) code to a different number so it draws a hexagon instead?
Hint
You need to change the 4 so it loops more times.
After that, experiment with adding more commands inside the loop with varying values and with different ranges.