Using Iteration (For Loops)

Contents
  1. Turtle with loops

1. Turtle with loops

Loops allow us to run blocks of code more than once (it allows us to be lazy). We can run the same code exactly or we can vary how it runs each time. We tend to use loops when our programs get longer or have lots of repetition.

The example below created a pentagon

import turtle

turtle.forward(100)
turtle.right(72)
turtle.forward(100)
turtle.right(72)
turtle.forward(100)
turtle.right(72)
turtle.forward(100)
turtle.right(72)
turtle.forward(100)

The code that makes up the pentagon contains a lot of repetition. We can optimise the code using a for loop:

import turtle

for i in range(5):
    turtle.forward(100)
    turtle.right(72)

Here we have told it to repeat 5 times. Indented code gets repeated. Each time it loops it draws a line and then turns right 72 degrees.

We can change the number inside the brackets in order to change the number of times the indented code repeats. We can even place other for loops inside for loops to create even more complicated graphics.