In the second programming assignment we are going to use the
turtle
module. turtle
mimics an old programming language Logo (Logo was actually my first
programming language).
from turtle import *
Recall this imports all the functions, etc. from the turtle
module into our
symbol table.
turtle
works by moving a “pen” around the screen, e.g.
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
for
loopsThat repetition is very tedious (and not very DRY). We know we want move and
turn 4 times. Can we loop over those statements 4 times? Yes. With a for
loop. A for
loop does exactly what it sounds like. For a specific set of
iterations, execute the enclosed statements. Note that we also convert that
fixed side length into function parameter that we can change.
def draw_square_with_loop(side_length):
for i in range(4):
forward(side_length)
right(90)
Note that “for” and “in” are reserved words (just like def
) and therefore
they cannot be used as variable or function names.
A for-loop generally:
range
function generates a sequence of integers starting at 0 up to but not
including the supplied stop parameter, e.g. 0, 1, 2, 3. So there will be 4
iterations. As we will see in future classes there are other kinds of
sequences.Let’s look at another example using loops, this time to print numbers:
def print_loop(n):
""" Print numbers from 0 until (but not including) n """
print("Begin list of numbers")
for i in range(n):
print(i)
print("End list of numbers")
>>> print_loop(5)
Begin list of numbers
0
1
2
3
4
End list of numbers
We can use the above output to remind us that there are three “regions” in and around our loop:
The statements inside the loop body will execute on every loop iteration, while the “after” statements will only execute once and only after all of the loop iterations are complete.
PI Questions (For loops)1
Recall in the first lecture that we said the computers were the right tool for the job when we needed to do something more than once. As you might imagine for-loops are one of our key tools for doing anything more than once. For example, when performing a computation “for each” data point in a file, or simulating a process “for” a set of different inputs.
turtle
errorsYou may encounter errors with turtle, including rendering again after a bye()
call. The graphics system that underlies turtle can only be “fired” once per
Python console session. You can restart the Python console by clicking the
“stop” sign to restart the Shell. Another warning, don’t name your file
“turtle.py”, doing so will prevent Python from finding the built-in turtle
functions.
We saw we can control the direction and angle of the drawing pen. What else can
we control to enhance our square? Lets check out the
docs. Here we change the
color of the line to be red and set the color of the interior of our square to
be yellow. The key for the “fill” is invoking begin_fill
before you draw the
shape and then end_fill
after you draw the shape.
pencolor("red")
fillcolor("yellow")
begin_fill()
draw_square_with_loop(100)
end_fill()
What about more interesting shapes? Specifically a Fibonacci spiral. A Fibonacci spiral is created by inscribing quarter circles inside squares whose edge length increases as the Fibonacci sequence. (Show code.)
def golden_spiral(radius, segments):
"""
Draw a Fibonacci spiral using Turtle. turtle package must be imported into namespace.
Args:
radius: Starting radius of the spiral
segments: Number of quarter circle segments to draw after initial quarter circle.
Must be >= 2.
Returns:
None
"""
circle(radius, 180)
a = radius
b = radius
for i in range(segments-2):
c = a + b
circle(c, 90)
a = b
b = c
Note that if we invoke the golden_spiral
function several times, each new
spiral starts from where the last one finished. This reminds us that the pen
has “state”, specifically an x and y position and a heading. Controlling that
state is a key part of the programming assignment.
Here are many more turtle examples for you to review in preparation for the programming assignment.
for
loops