14.3. 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.
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
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.
Discuss topics in this section with classmates.