Elif

Estimated Time: 15 minutes


Snakes around a birthday cake

If-elif statements

if and else let us express conditions with two possible outcomes. But what if there are more than two possibilities we want to express in our program? elif stands for "else if". It lets us check more conditions, so we can cover as many conditions as we want.

Below is the flow control diagram for a multi-branch program:

multi-way-flowchart

Here is the corresponding Python code:

if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')

The code runs line by line. So, the conditions are checked in the order the code is written. The code does not look ahead. So, in the example above, assuming x = 3 and y = 3, the code will do 2 comparisons:

  • Check if x is less than y. Since x = 3 and y = 3 this statement is false, and it keeps going
  • Check if x is greater than y. Since x = 3 and y = 3, this statement is false
  • Execute the else statement and print 'x and y are equal'

But with x = 4 and y = 6, the code will run the first comparison, print 'x is less than y' and finish. It will never even run the second check!

There is no limit on the number of elif statements that can be added, but the code will evaluate them from top to bottom. Having an else statement is optional, but if you have one, it has to be at the end.

Practice

2%202%20Multi-way%20decisions%205adb8178795a43bf9ff453def27f562e/Screen_Shot_2021-07-27_at_3.10.10_PM.png

Sample run of the code now look like this:

2%202%20Multi-way%20decisions%205adb8178795a43bf9ff453def27f562e/Untitled%202.png