Learn Python / If / Elif / Else

If / Elif / Else

Up to now, every line of every program has run, top to bottom. Real programs need to make decisions: show an error if the password is wrong, give a discount if the order is big enough. That's what if statements are for.

The if statement

An if statement runs a block of code only when a condition is True:

temperature = 30

if temperature > 25:
    print("It's a hot day!")
    print("Remember to drink water.")

print("This line always runs.")
Output

Change temperature to 20 and run it again. The two indented lines are skipped.

Notice the two key parts:

  1. The line ends with a colon :.
  2. The code that belongs to the if is indented (4 spaces is the standard).

Indentation matters

In many languages, braces { } group code. Python uses indentation instead. Every line indented under the if belongs to it, and the first line back at the original level ends the block.

If you forget to indent, Python raises an IndentationError:

age = 20
if age >= 18:
print("You can vote.")
Output

else: the other path

else runs when the condition is False:

age = 15

if age >= 18:
    print("You can vote.")
else:
    print("You can't vote yet.")
    print(f"Only {18 - age} more years to go!")
Output

Exactly one of the two blocks always runs, never both.

elif: more than two choices

When there are several possibilities, use elif (short for "else if"). Python checks each condition from top to bottom and runs the first one that's True:

Predict first: with score = 72, which grade will be printed? Then change score to 95 and 55 and predict again.

score = 72

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score {score} gets grade {grade}")
Output

Order matters. A score of 95 is also >= 70, but because score >= 90 is checked first, it gets an A. Once one branch runs, the rest are skipped.

Combining conditions

Use and, or and not from the previous lesson to build richer conditions:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive.")
elif age >= 18:
    print("You need a license first.")
else:
    print("You're too young to drive.")
Output

Using truthiness

Because empty strings are falsy, you can check whether the user typed anything with just if name::

name = input("What's your name? (or just press Enter) ").strip()

if name:
    print(f"Hello, {name}!")
else:
    print("Hello, stranger!")
Output

Nested if statements

You can put an if inside another if. Each level is indented further:

number = 14

if number > 0:
    if number % 2 == 0:
        print("Positive and even")
    else:
        print("Positive and odd")
else:
    print("Zero or negative")
Output

Deep nesting gets hard to read. You can often flatten it with and or elif.

The conditional expression

For simple choices between two values, Python has a one-line form:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)

number = 7
print("even" if number % 2 == 0 else "odd")
Output

Read it as: value_if_true if condition else value_if_false.

Going deeper: match: choosing between exact values optional

When you compare one value against a list of exact options, a long elif chain gets repetitive. Python 3.10 added match, which reads more like a menu:

command = "stop"

match command:
    case "start":
        print("Starting the engine")
    case "stop":
        print("Stopping")
    case "pause" | "wait":
        print("Pausing for a moment")
    case _:
        print("Unknown command")
Output
  • Each case lists a value to match. | means "or", so "pause" | "wait" matches either.
  • case _: matches anything else, like a final else.
  • Only the first matching case runs.

match is best for exact values like commands or menu choices. For ranges such as score >= 90, stick with if/elif.

Going deeper: Empty blocks with pass optional

A block can't be empty. If you want a placeholder that you'll fill in later, write pass, which means "do nothing":

level = 3

if level > 5:
    pass   # TODO: handle advanced levels later
else:
    print("Keep practising!")
Output

Common mistakes

Mistake Wrong Right
Using = instead of == if x = 5: if x == 5:
Missing colon if x > 5 if x > 5:
Missing indentation print(...) at the same level as if indent by 4 spaces
Repeating the variable if x == 1 or 2: if x == 1 or x == 2:

The last one is sneaky. x == 1 or 2 is always truthy because 2 on its own is truthy:

x = 5

if x == 1 or 2:
    print("This runs, even though x is 5!")

if x == 1 or x == 2:
    print("This one is correct, so it doesn't run.")
Output

Exercises

Exercise 1: Even or odd

Print Even if number is even, otherwise print Odd.

number = 17
Output

Exercise 2: Largest of three

Print the largest of the three numbers using if / elif / else, without using max().

a = 12
b = 31
c = 7
Output

Exercise 3: Ticket price

A cinema charges: children under 12 pay 5, people 65 and over pay 6, and everyone else pays 10. Ask the user for their age and print their ticket price.

# Ask for age and print the ticket price
Output

Exercise 4: Leap year

A year is a leap year if it's divisible by 4, except years divisible by 100, unless they're also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not. Print whether year is a leap year.

year = 1900
Output

Summary

  • if condition: runs the indented block only when the condition is true.
  • else: runs when it's false, and elif adds more choices. The first true branch wins.
  • Python uses indentation (4 spaces) to group code, and a colon starts every block.
  • Combine conditions with and, or and not, and use truthiness for quick checks like if name:.
  • a if condition else b picks between two values in one line.
  • Use == to compare, and repeat the variable in each part of an or.