Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

56 Chapter 4


numbers, you can enter different numbers inside the parentheses
of the range() function:

>>> list(range(3))
[0, 1, 2]
>>> list(range(5))
[0, 1, 2, 3, 4]

As you can see, entering list(range(3)) gives you a list of three
numbers starting at 0, and entering list(range(5)) gives you a list
of five numbers starting at 0.

Using a for Loop to Make a Rosette with Four Circles


For our four-circle rosette shape, we need to repeat drawing a
circle four times, and range(4) will help us do that. The syntax,
or word order, of our for loop will look like this:

for x in range(4):

We start with the keyword for and then we give a variable,
x, that will be our counter or iterator variable. The in keyword
tells the for loop to step x through each of the values in the range
list, and range(4) gives the loop a list of the numbers from 0 to 3,
[0,1,2,3], to step through. Remember that the computer usually
starts counting from 0 instead of starting from 1 as we do.
To tell the computer which instructions are supposed to be
repeated, we use indentation; we indent each command that we
want to repeat in the loop by pressing the tab key in the new
file window. Type this new version of our program and save it as
Rosette4.py.

Rosette4.py

import turtle
t = turtle.Pen()
for x in range(4):
t.circle(100)
t.left(90)

This is a much shorter version of our Rosette.py program,
thanks to the for loop, yet it produces the same four circles as
the version without the loop. This program loops through lines 3,
Free download pdf