Skip to main content

If Statements

Making Your Code Choose

· 3 min read

In the previous unit, we covered operators and boolean logic. Those comparisons that return True or False? Now we put them to work. Conditional statements let your program make decisions based on those boolean results.

If Statements

The if Statement

The if statement executes a block of code only when a condition is true. The condition is any expression that evaluates to True or False.

x = 10
if x > 5:
print("x is greater than 5")

If x > 5 evaluates to True, the indented code runs. If it's False, Python skips it entirely. Indentation matters here. Everything indented under the if belongs to that block.

Adding else and elif

Sometimes you want to do something when the condition is false. That's what else is for.

x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")

When you need to check multiple conditions, elif (short for "else if") handles the in-between cases.

x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 15")

Python evaluates conditions from top to bottom. Once one condition matches, it runs that block and skips the rest. The else at the end catches anything that didn't match earlier conditions.

Nesting Conditionals

You can put an if inside another if. This is nesting, and it's useful when you need to check multiple related conditions.

x = 10
if x > 0:
if x % 2 == 0:
print("x is a positive even number")
else:
print("x is a positive odd number")
else:
print("x is not a positive number")

Indentation is critical with nesting. Each level of if requires another level of indentation. If your indentation is off, the code won't behave the way you expect.

Project: Draw Colored Shapes

Let's combine conditionals with Turtle graphics. This program asks for a number of sides and draws a shape in a color that matches.

import turtle

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()

num_sides = int(input("Enter the number of sides (3 to 5): "))

if num_sides == 3:
t.color("red")
elif num_sides == 4:
t.color("blue")
elif num_sides == 5:
t.color("green")
else:
print("Please enter a number between 3 and 5.")
quit()

for _ in range(num_sides):
t.forward(100)
t.right(360 / num_sides)

turtle.done()

We use int(input(...)) to get a number from the user. The if/elif chain assigns a color based on that number: red for triangles, blue for squares, green for pentagons. If the input is outside the range, we print a message and exit with quit().

The drawing logic uses what we learned about loops. The angle calculation 360 / num_sides ensures the turtle turns the right amount for each shape.

In the next unit, we'll look at match-case, a cleaner way to handle situations where you're comparing one value against several possibilities.