Main Content

If elif elif elif - multiway selection in Python

Archive - Originally posted on "The Horse's Mouth" - 2013-11-16 16:13:28 - Graham Ellis

Most languages have "if / else if / else if / else " type constructs for selecting conditional code, although the format / keyword varies between languages, in the case if Python, the intermediate keyword is elif.

In all cases with this construct, you can think of it as like peeling an onion - taking a specific condition and dealing with it, and leaving other conditions in a subset to be considered later. In other words, once one option has been found that's true, the other options won't be checked nor will any further conditional code blocks be checked.

For example:

  if trainsPerDay == 8:
     a()
  elif trainsPerDay > 6 and trainsPerDay < 20:
     b()
  elif trainsPerDay > 6:
     c()
  etc


a() will be run in the value in trainsPerDay was 8.

If the value is between 6 and 20 BUT IS NOT 8, then b() will be run. b() isn't run if the tested value is 8, because that's already been dealt with in the earlier test.

c() says it will be run if the value is greater that 6. However, 8 was dealt with in the first test, and values between 6 and 20 in the second test, so in practice c() won't run until trainsPerDay is 20 or greater.

You could (rightly) suggest that my example could have been more clearly coded - but then it would have failed to make the point so clearly. Only one block will be performed, and you need to be very careful to put your blocks in the right order if you can hit a situation in which several would be true. And it's first matched, first run in that circumstance.

Source code examples [here] and [here].

I have just finished teaching learning to program in Python and Python Programming for 2013... next week I am teaching the more advanced Python Intermediate. Please get in touch is you want to make an extraordinarily late booking... or follow the links above which will give you a whole list of public course dates for each of the three courses for 2014.