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

(vip2019) #1

88 Chapter 5


Even or Odd?


The if-else statement can test more than user input. We can use it
to alternate shapes, like in Figure 5-1, by using an if statement to
test our loop variable each time it changes to see if it’s even or odd.
On every even pass through the loop—when our variable is equal
to 0 , 2 , 4 , and so on—we can draw a rosette, and on every odd pass
through the loop, we can draw a polygon.
To do this, we need to know how to check if a number is odd or
even. Think about how we decide if a number is even; that means
the number is divisible by two. Is there a way to see if a number
is evenly divisible by two? “Evenly divisible” means there’s no
remainder. For example, four is even, or evenly divisible by two,
because 4 ÷ 2 = 2 with no remainder. Five is odd because 5 ÷ 2 = 2
with a remainder of 1. So even numbers have a remainder of zero
when they’re divided by two, and odd numbers have a remainder
of one. Remember the remainder operator? That’s right: it’s our old
friend the modulo operator, %.
In Python code, we can set up a loop variable m and check to
see if m is even by testing m % 2 == 0—that is, checking to see if the
remainder when we divide m by two is equal to zero:

for m in range(number):
if (m % 2 == 0): # Tests to see if m is even
# Do even stuff
else: # Otherwise, m must be odd
# Do odd stuff

Let’s modify a spiral program to draw rosettes at even corners
and polygons at odd corners of a big spiral. We’ll use a big for loop
for the big spiral, an if-else statement to check whether to draw
a rosette or a polygon, and two small inner loops to draw either a
rosette or a polygon. This will be longer than most of our programs
so far, but comments will help explain what the program is doing.
Type and run the following program, RosettesAndPolygons.py, and
be sure to check that your indentation is correct for the loops and
if statements.
RosettesAndPolygons.py

# RosettesAndPolygons.py - a spiral of polygons AND rosettes!
import turtle
t = turtle.Pen()
Free download pdf