Conditional
Deprecated Lab — Trinket is shutting down
This lab was written for Trinket.io, which is shutting down in August 2026. The embedded trinket.io links on this page will stop working after that date.
These pages are kept for reference only. The current version of this course now runs every lab as an inline Skulpt editor right in the page — no account or install needed. Start at Chapter 1: Welcome to Python.
Conditionals¶
In this example program we will make the turtle draw different sides of the square using different colors.
There are two things we do with equations in Python. The first is to use the equal sign to assign values on the left side of the equal sign to the values on the right side. The second thing we do is to compare values to the left and right of an operator. The result of a comparison is always TRUE or FALSE.
Here is the basic syntax of the Python conditional operator.
1 2 3 4 | |
Simple Conditionals¶
Here is a program that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Link to Trinket with Simple Conditional
Changing Odd and Even Edge Colors¶
We would like every other side to change color. To do this we will add an if-then-else block of code to our example program. This block of code is called a conditional block. The condition is an expression that evaluates to be either TRUE for FALSE. In our example we will test to see if the index of our loop (the letter "i") is ODD or EVEN. We can do this by looking at the remainder after we divide by 2. Python has a handy operator called the modulo operator that uses the percent character which is above the number five on your keyboard. The test for ODD or EVEN is this:
1 | |
In our previous loop lesson, we created an index that started at 1 and then changed to 2, 3 and finally 4. For 1 and 3, the first and third edges the result of divide by 2 will return 1 which is the same as TRUE. For 2 and 4 (the vertical sides of the square), the expression will evaluate to 0 since the remainder of 2/2 and 4/2 is zero.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Can you make the turtle use a larger pen size? Try dan.pensize(10) for the red and dan.pensize(3) for the blue.
Experiments¶
- Can you change the width of the pen with the dan.penwidth(20) function?
- Show i
1 2 3 4 5 6 7 8
for i in range(4): dan.write(i ,None,None, "16pt bold") if i % 2: dan.color('red') else: dan.color('blue') dan.forward(distance) dan.right(angle)