Hardware Reference
In-Depth Information
You should use the text editor for the remainder of this adventure.
Using “for” Loops and Lists
In your Python code so far, you have repeated the length of the line and the angle to
make a pentagon shape by writing them in sequence. Repeating sequences is a com-
mon practice in computer science. You can make this code more eicient by writing
the sequence once and then looping it ive times. You have used looping before in
Scratch, when you used the forever block to make an action continue repeating. As you
learned in Adventure 3, each repeated instance of the looping code lines is called an
iteration .
Quite often, you will want your code to repeat or loop. In Scratch, you use
the repeat or forever blocks to iterate. In Python you can use a for loop.
To practice looping code, open a new text editor window and type the following code,
saving the ile as FirstTurtle2.py.
import turtle
alex = turtle.Turtle()
alex.shape(“turtle”)
Next add a for loop:
for i in [0,1,2,3,4,]:
alex.forward(100)
alex.left(72)
his code says, “for each instance ( i ) in the following list, move alex forward 100 steps
and then turn left 72 degrees”.
When you have inished typing the code, run it by selecting Run Run Module.
he for statement will repeat forward and left ive times, one time for each
value in the list. A list is represented in Python by square brackets. Numbered lists
begin at 0 rather than 1. If you had written 0,1,2,3, inside the square brackets to form
a list, then only four sides of the pentagon shape would be drawn. Likewise if you had
written 0,1,2,3,4,5, then six sides of the pentagon shape would be drawn, which is one
side too many! Have a go yourself to see how numbering inside Python lists work.
Search WWH ::




Custom Search