the full guide

If, elif and else: making decisions

Make your program choose what to do, and learn why indentation matters.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

if and else

if_else.py
marks = 72

if marks >= 40:
    print("Pass")
    print("Well done!")
else:
    print("Try again")

print("This line always runs")

Output

Pass
Well done!
This line always runs

elif: more than two choices

Python checks from the top and stops at the first true condition.

elif.py
marks = 72

if marks >= 90:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"

print("Grade:", grade)

Output

Grade: B

Nested if, one-line if, pass and match

if_more.py
age = 20
has_licence = True

# An if inside an if
if age >= 18:
    if has_licence:
        print("You can drive")

# One line
label = "adult" if age >= 18 else "minor"
print(label)

# pass means "nothing here yet"
if age > 100:
    pass

# match compares one value with many options
day = 6
match day:
    case 6 | 7:
        print("Weekend")
    case _:
        print("Weekday")

Output

You can drive
adult
Weekend

Code challenge

Print “Even” or “Odd” for a number.

if n % 2 == 0: print("Even"), else: print("Odd"). The remainder after dividing by 2 tells you.

Finished reading?