Another Function and a For Loop Introduction

Now that we know what a function is, how they look, and how we can use them, let’s reinforce that knowledge by making another. This function will have our turtle draw a spiral shape, taking advantage of a for loop. As it goes, it will turn some constant amount, but move further forward each time that the loop runs.

First things first, define a function named “spiral”

def spiral():

Recall from last lesson that we did create a loop, but it was a while loop. For this project we are going to use a for loop. A for loop will run through a python object called a list, and do something once for each item in the list. A list is basically what it sounds like. It can be a list of numbers, words, characters, or any other object you can make with python. You can even have a list of other lists. We will cover lists in some more detail in the next lesson, but for now, it helps to understand what they are so we can better understand whats happening when we create a for loop

Now that we’ve talked about lists, let’s look at the syntax of a for loop. Inside our spiral function, code the following

def spiral():
    for number in range(360):

What this line of code will do is create a temporary variable named “number”, and set it to every number in the list “range(360)”. So what’s range(360)? The function “range” will automatically create a list of every number between 0 and whatever number we give it. So this loop will run once for every number from 0 to 360, and then stop. Now, lets go ahead and program it to actually do the loop.

For this program we are going to have the turtle move right by some constant degree, and move forward by whatever number we’re currently on in the loop. Feel free to experiment with both how far the turtle turns in turtley.right() , and the number of loops in range()

def spiral():
    for number in range(360):
        turtley.forward(number)
        turtley.right(20)

Now that we have a function for the spiral, we can call it just like our jump function

turtley.forward(50)
spiral()
jump()
spiral()