🔀 Selection

Learn how to make decisions in your code using if statements.

What you'll learn:

  • How to use if statements to make decisions
  • Comparison operators: ==, !=, <, >, <=, >=
  • Boolean operators: and, or, not
  • Using if-else for two-way decisions
  • Using if-elif-else for multiple options

Learning Path

Follow these activities in order.

Comparison Operators

Use these to compare two values. The result is always True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than5 > 3True
<=Less than or equal5 <= 5True
>=Greater than or equal5 >= 3True

Boolean Operators: and, or, not

Combine multiple conditions together to make more complex decisions.

and

Both conditions must be True for the result to be True.

age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("You can enter")
ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or

At least one condition must be True for the result to be True.

is_student = True
is_senior = False

if is_student or is_senior:
    print("You get a discount")
ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

not

Reverses the condition. True becomes False, False becomes True.

logged_in = False

if not logged_in:
    print("Please log in")
Anot A
TrueFalse
FalseTrue

Key Vocabulary

selection

Choosing which code to run based on a condition. Also called branching.

condition

An expression that is either True or False. age >= 18

if statement

Runs code only if a condition is True. if score > 50:

else

Code that runs when the if condition is False.

elif

Short for "else if". Checks another condition if the first was False.

comparison operator

Symbols that compare values: == != < > <= >=

Boolean

A value that is either True or False. Named after mathematician George Boole.

and operator

Combines conditions: both must be True. x > 0 and x < 10

or operator

Combines conditions: at least one must be True. x == 0 or x == 1

not operator

Reverses a condition. not logged_in

Quick Reference

selection_preview.py
# Simple if statement
age = 15
if age >= 13:
    print("You're a teenager!")

# if-else: two options
score = 45
if score >= 50:
    print("Pass")
else:
    print("Fail")

# if-elif-else: multiple options
grade = 75
if grade >= 90:
    print("A")
elif grade >= 70:
    print("B")
elif grade >= 50:
    print("C")
else:
    print("Fail")

# Using Boolean operators
age = 25
has_licence = True

# and: both conditions must be True
if age >= 18 and has_licence:
    print("You can drive")

# or: at least one must be True
if age < 12 or age > 65:
    print("Free ticket")

# not: reverses the condition
logged_in = False
if not logged_in:
    print("Please log in")