Loops are used when you have a block of code that you want to repeat.
A for loop is used when you have a block of code which you want to repeat a fixed number of times. The for loop iterates through the block of indented code.
for x in range():
x is a variable that steps through values
<do something>
do something in the indented block
for.py
for x in range(4):
print(x)
$ python for.py
0
1
2
3
4
Square
square2.py
import turtle
turtle.showturtle()
turtle.shape("turtle")
for x in range(4):
turtle.forward(50)
turtle.right(90)
Spiral
spiral2.py
import turtle
length = 10
angle = 90
turtle.showturtle()
turtle.shape("turtle")
for x in range(10):
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
spiral3.py
import turtle
angle = 91
turtle.showturtle()
turtle.shape("turtle")
for x in range(100):
turtle.forward(x)
turtle.left(angle)
circle.py
import turtle
angle = 91
turtle.showturtle()
turtle.shape("turtle")
for x in range(100):
turtle.circle(x)
turtle.left(angle)
Polygons
Shape
Sides
Interior Angle
Triangle
3
60
Quadrilateral
4
90
Pentagon
5
108
Hexagon
6
120
Heptagon
7
128.571
Octagon
8
135
Nonagon
9
140
Decagon
10
144
Hendecagon
11
147.273
Dodecagon
12
150
triangle.py
import turtle
length = 100
angle = 120
turtle.showturtle()
turtle.shape("turtle")
for i in range(3):
turtle.forward(length)
turtle.right(angle)
Star
Using a loop, we can produce an eight point star.
star1.py
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('green')
for x in range(13):
turtle.forward(200)
turtle.left(150)
What happens if we try changing the range and the left angle?
star2.py
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('purple')
for x in range(100):
turtle.forward(200)
turtle.left(175)
Spiral Circle
spiral.py
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('pink')
for i in range(180):
turtle.forward(100)
turtle.right(30)
turtle.forward(20)
turtle.left(60)
turtle.forward(50)
turtle.right(30)
turtle.penup()
turtle.setposition(0, 0)
turtle.pendown()
turtle.right(2)