Detecting Odd and Even¶
One common thing to do with conditionals is to check if a number is odd or even. If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator
% like this
num % 2 == 0. If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using
num % 2 == 1. The code below uses two
if statements to check if the current value of
y is even or odd. It uses this to draw two alternating color stripes.
The code below uses the
window_width() function of the
Screen object that returns the width of the Screen (drawing area). There is also a
window_height() function that returns the height of the Screen (drawing area).
This code calculates
maxX as half the width of the drawing space. This is used to determine the x value for the left side of the window. The left side is at
-1 * maxX since the window uses the cartesian coordinate system with (0,0) as the center of the window.
For more information on what this code is doing listen to the audio tour.
- This will stop before filling the top half of the space. Try it.
- The turtle starts at the middle of height and draws 5 pixels below it and 5 pixels above it, so this leaves 5 pixels at the top that need to be filled.
- The height of the top half is 160 and each stripe is a height of 10 so 16 nearly does it, but 17 fills the entire area. The turtle starts in the middle of the space so the first row has 5 pixels above the middle and 5 below.
- This would fill more than the top half.
csp-14-3-2: What value should you use as the parameter for the range function in line 12 to fill the top half of the drawing space with stripes? The height of the space is 320.
Try to change the code above to use an
else instead of the second
if and yet still have the same result.
Try to change the code above to use both an
else to draw three different colored stripes in a repeated pattern. You can use
y % 3 for three different conditions.
Mixed up programs
csp-14-3-3: The following program should draw vertical color stipes alternating between red and black, but the code is mixed up. Drag the block from left to right and place them in the correct order with the correct indention.from turtle import * space = Screen() height = space.window_height() --- maxY = height / 2 sue = Turtle() sue.pensize(10) sue.left(90) --- for index in range(5): --- sue.penup() --- if index % 2 == 0: --- sue.color('red') --- else: --- sue.color('black') --- sue.goto(index * 10, -1 * maxY) sue.pendown() sue.forward(height)
Discuss topics in this section with classmates.