Python For Kids (Level1-Level 2) 3rd - Week
Python For Kids (Level1-Level 2) 3rd - Week
Chapter 4
Loops Are Fun
We’ve used loops since our very first program to draw repeating shapes. Now it’s time to learn
how to build our own loops from scratch. Whenever we need to do something over and over
again in a program, loops allow us to repeat those steps without having to type each one
separately. Figure 4-1 shows a visual example — a rosette made up of four circles.
Rosette.py
import turtle
t = turtle.Pen()
t.circle(100)
# This makes our first circle (pointing north)
t.left(90) # Then the turtle turns left 90 degrees
t.circle(100) # This makes our second circle (pointing west)
t.left(90) # Then the turtle turns left 90 degrees
t.circle(100) # This makes our third circle (pointing south)
t.left(90) # Then the turtle turns left 90 degrees
t.circle(100) # This makes our fourth circle (pointing east)
This code works, but doesn’t it feel repetitive? We typed the code to draw a circle four times
and the code to turn left three times.
To build our own loop, we first need to identify the repeated steps. The instructions that we’re
repeating in the preceding code are t.circle(100) to draw a turtle circle with a radius of 100 pixels and
t.left(90) to turn the turtle left 90 degrees before drawing the next circle.
Second, we need to figure out how many times to repeat those steps. We want four circles, so let’s
start with four.
Now that we know the two repeated instructions and the number of times to draw the circle, it’s
time to build our for loop.
A for loop in Python iterates over a list of items, or repeats once for each item in a list — like the
numbers 1 through 100, or 0 through 9. We want our loop to run four times — once for each circle — so
we need to set up a list of four numbers.
we get six circles around the center of the screen this time, as shown in Figure 4-2
RosetteGoneWild.py
import turtle
t = turtle.Pen() # Ask the user for the number of circles in their rosette, default to 6
number_of_circles = int(turtle.numinput("Number of circles", "How many circles in your rosette?", 6))
for x in range(number_of_circles):
t.circle(100)
t.left(360/number_of_circles)
For example, if the user enters 30 as the number of circles, 360 ÷ 30 would give us a 12-degree turn
between each of the 30 circles around our center point, as shown in Figure 4-3
Figure 4-4. A little imagination and a touch of code can turn our rosette program into a lot of colorful fun!