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.

    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.

  • 10
  • This will stop before filling the top half of the space. Try it.
  • 16
  • 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.
  • 17
  • 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.
  • 32
  • This would fill more than the top half.

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 elif and 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()
for index in range(5):
    if index % 2 == 0:
    sue.goto(index * 10, -1 * maxY)


Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page