Python Tutorials · Python If...Else

Python Elif

Learn all about Python Elif in this comprehensive tutorial.

5 min read beginner
  • The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
  • You can have as many elif statements as you need.
  • When you use elif, Python evaluates the conditions from top to bottom.
  • Use elif when you have multiple mutually exclusive conditions to check.

The Elif Keyword

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

The elif keyword allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

python

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".

Multiple Elif Statements

You can have as many elif statements as you need. Python will check each condition in order and execute the first one that is true.

python

In this example, the program checks each condition in order. Since score is 75, it prints "Grade: C" (the first condition that evaluates to true).

How Elif Works

When you use elif, Python evaluates the conditions from top to bottom. As soon as it finds a condition that is true, it executes that block and skips all remaining conditions.

Note: Important: Only the first true condition will be executed. Even if multiple conditions are true, Python stops after executing the first matching block.
python

When to Use Elif

Use elif when you have multiple mutually exclusive conditions to check. This is more efficient than using multiple separate if statements because Python stops checking once it finds a true condition.

python

Module quiz

2 questions
1

Which of the following is true about Python Elif?

2

What is the most common pitfall when working with Python Elif?

Answer all questions to submit.