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

(vip2019) #1
Loops Are Fun (You Can Say That Again) 73

What You Learned


In this chapter, you learned to build your own loops by identify-
ing repeated steps in a program and moving those repeated steps
inside the right kind of loop. With a for loop, you can run your
code a set number of times, like looping 10 times with for x in
range(10). With a while loop, you can run your code until a condi-
tion or event occurs, like the user entering nothing at an input
prompt with while name != "".
You learned that the flow of a program is changed by the loops
that you create. We used the range() function to generate lists of
values that allow us to control the number of times our for loops
repeat, and we used the modulo operator, %, to loop through the
values in a list to change colors in a list of colors, pick names out
of a list of names, and more.
We used an empty list, [], and the append() function to add
information from the user into a list that we then used in a pro-
gram. You learned that the len() function can tell you the length
of a list—that is, how many values the list contains.
You learned how to remember the turtle’s current position and
the direction it’s heading with the t.position() and t.heading() func-
tions, and you learned how to get the turtle back to this location
and heading with t.setx(), t.sety(), and t.setheading().
Finally, you saw how you can use nested loops to repeat one
set of instructions inside another set, first to print a list of names
on a screen and then to create spirals of spirals in a kaleidoscope
pattern. Along the way, we’ve drawn lines, circles, and strings of
words or names on the screen.
At this point, you should be able to do the following:
• Create your own for loops to repeat a set of instructions a cer-
tain number of times.
• Use the range() function to generate lists of values to control
your for loops.
• Create empty lists and add to lists using the append() function.
• Create your own while loops to repeat while a condition is True^
or until the condition is False.
• Explain how each type of loop works and how you code it in
Python.
Free download pdf