Making Decisions with If Statements Jump to this section
If statements let your code choose different actions depending on conditions. This helps make drawings react to values.
Basic if example
Jump to this section
import turtle
size = 80
t = turtle.Turtle()
if size > 50:
t.pencolor('red')
else:
t.pencolor('blue')
t.forward(size)
Here the pen color depends on whether size is larger than 50.
Using if inside a loop to vary appearance
Jump to this section
import turtle
t = turtle.Turtle()
for i in range(8):
if i % 2 == 0:
t.pencolor('green')
else:
t.pencolor('purple')
t.forward(80)
t.left(45)
The loop alternates colors using a simple condition i % 2 == 0, which returns True if i is even.
Combining conditions Jump to this section
import turtle
size = 60
t = turtle.Turtle()
if size > 100:
t.pensize(5)
elif size > 50:
t.pensize(3)
else:
t.pensize(1)
t.forward(size)
Exercise Jump to this section
- Use an
ifstatement to choose a different shape to draw based on a variablechoice. (Make sure to use==to check if things are equal, not=). For help withifstatements, check out Python Conditionals.
