Skip to main content

The Elif Keyword

With elif, Python says: "the conditions so far were not true, so try this one next".

This lets you test several expressions in turn. The block belonging to the first expression that evaluates to True is the one that runs.

Example

Prompt
Write a Python program that uses if and elif to compare two equal variables and print a message when they are equal.
Output: complete Python program

Multiple Elif Statements

There is no limit on how many elif statements you can write. Python goes through them in order and runs the block of the first condition that turns out true.

Example

Several conditions in a row:
Prompt
Write a Python program that assigns a score of 75 and uses multiple elif statements to determine and print the letter grade.
Output: complete Python program

How Elif Works

Python works through an elif chain from top to bottom. The moment one condition is true, its block runs and the rest of the chain is skipped.

Important: More than one condition may be true, but only the block of the earliest one runs. Python never goes on to the others.

Example

Sorting people into age groups:
Prompt
Write a Python program that categorizes an age of 25 into child, teenager, adult, or senior using if and elif.
Output: complete Python program

When to Use Elif

Reach for elif when your conditions rule each other out. A chain like this is more efficient than a row of separate if statements, since the checking ends as soon as one condition is true.

Example

Turning a number into a weekday:
Prompt
Write a Python program that converts a day number (3) to the corresponding day name using if and elif.
Output: complete Python program