Chained If Statements Using ELIF & ELSE

It is certainly possible to use and and or to ensure that only one if statement in a chain gets run. But it is annoying, and a single mistake can mess up the whole thing.

So what programmers usually use is elif and else. Here is an example!

human-age-with-else.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from __future__ import print_function
input = raw_input

age = float(input("How old is the human? "))
term = 'unknown'

if age < 0 or age > 150:
    print("That's unlikely.")
    term = 'improbable'
elif age < 1:
    term = 'baby'
elif age < 3:
    term = 'toddler'
elif age < 5:
    term = 'preschooler'
elif age < 9:
    term = 'child'
elif age < 13:
    term = 'preteen'
elif age < 18:
    term = 'teen'
elif age < 40:
    term = 'young adult'
elif age < 65:
    term = 'adult'
else:
    term = 'elderly'

if term == 'unknown':
    print("You did something wrong, but I'm not sure what.")
else:
    print("A human {} years old is usually called '{}'.".format(age, term))

What You Should See

How old is the human? 42
A human 42.0 years old is usually called 'adult'.

elif is pretty simple. It is just like an if statement, but it checks two things.

  1. Is the elif's condition true?
  2. Is the opposite of the previous if or elif statement true?

(elif is an abbreviation for "else if")

When the previous statement was false and the elif's condition is true, then its code gets run. Basically exactly what we did manually in the previous exercise.

The else statement is even simpler. The else's code gets executed if the previous statement was false.

In this program, the elif on line 10 only runs if age is less than 1 and the if statement from line 7 was false.

The elif on line 12 only gets a shot if the one on line 10 was false.

The elif on line 14 only gets a chance when the elif on line 12 was false.

And so on. The else on line 26 only runs if all the previous conditions were false.

Study Drills

  1. Add the same if statement here that you did in the previous exercise, but use elif this time. Was it easier? Answer in a comment.



©2017 Graham Mitchell