Looping turtles
Earlier, our turtle has drawn a square according to our instructions. But our instructions repeated themselves: Walk 100 steps, turn 90 degrees left, and then do the same thing four times, once for each side of the square.
But this repetition must mean one thing: We can use a loop!
Repeated sides
If we can find a pattern in what we're trying to do, we can express it much simpler and more powerful. When we draw the square we're doing the same thing four times:
# Walk forward 100 steps
# Turn 90 degrees to the left
# Walk forward 100 steps
# urn 90 degrees to the left
# Walk forward 100 steps
# Turn 90 degrees to the left
# Walk forward 100 steps
# Turn 90 degrees to the left
That means we'd rather express it as such:
for i in range(0, 4):
# Walk forward 100 steps
# Turn 90 degrees to the left
A complete program can therefore be this short::
from turtle import *
color('blue')
for i in range(0, 4):
forward(100)
left(90)
Generalisation
In science, mathematics, and programming, finding a pattern and writing something general about that is a strength - finding one formula that expresses a deep connection.
Earlier, we wrote a program to pick what shape the turtle should draw and had square and triangle as alternatives. But what if we wanted more?
The angle sum of a regular geometric shape with n sides can be calculated with the following formula:
$$\texttt{Angles sum}=180\cdot(n-2)$$
That means each inner angle, with n sides, is:
$$\text{Angle} = \frac{\texttt{Angles sum}}{n}=\frac{180\cdot(n-2)}{n}$$
The turtle needs to turn the outer angle of this, so we need to subtract this from 180:
$$\text{Angle} = 180 - \frac{\texttt{Angles sum}}{n}=180 - \frac{180\cdot(n-2)}{n}=180\cdot\frac{2}{n}$$
Using this formula, the turtle can draw any regular geometric shape!
We start by including the parts we need:
import turtle
turtle.color('red')
Then, we need to ask how many sides to draw:
n = int(input("How many sides?"))
We can even ensure that it's not wrong. For example, the user might enter 2 or 1, or even a negative number. That's not enough for a proper geometric figure. We need at least 3 sides, and we can solve that with an if-statement:
if n < 3:
print("You must enter at least 3 sides")
n = 3
Once we know the number of sides we can use the formula above to calculate how much to turn:
angle = 180*(2/n)
What's left? We use the same loop as before, but with the variable angle instead of 90:
for i in range(0, n):
turtle.forward(100)
turtle.left(angle)
Here's the complete program:
But this code is missing comments. Where would you add them?
In this video, we use for-loops to draw more intricate turtle patterns.
- Formula: Is a mathematical expression that describes a specific law or rule.
- If-statement: The keyword "if" followed by a logical condition allows our program to make decisions.