Ethan Bierlein
Ethan Bierlein

Reputation: 3535

"if", and "elif" chain versus a plain "if" chain

I was wondering, why is using elif necessary when you could just do this?

if True:
    ...
if False:
    ...
...

Upvotes: 2

Views: 1259

Answers (2)

kojiro
kojiro

Reputation: 77059

itertools.count is a generator that gives you a new value each time it's called, so it's useful for illustrating this kind of thing.

from itertools import count
c = count()
print(next(c)) # 0
print(next(c)) # 1
print(next(c)) # 2
if True:
  print(next(c)) # 3
if True:
  print(next(c)) # 4
elif True:
  print(next(c)) # … not called
print(next(c)) # 5

The last value would have to be 6 for the elif to be the same as the if. But generators can also be "used up", which means you need to be able to avoid checking them twice.

if 6 == next(c):
  print('got 6') # Printed!
if (7 == next(c)) and not (6 == next(c)):
  print('got 7') # Also printed!

is not the same as

if 9 == next(c):
  print('got 9') # printed
elif 10 == next(c):
  print('got 10') # not printed!

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121436

You'd use elif when you want to ensure that only one branch is picked:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
elif spam == 'eggs':
    # won't do this.

Compare this with:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
if spam == 'eggs':
    # *and* do this.

With just if statements, the options are not exclusive.

This also applies when the if branch changes the program state such that the elif test might be true too:

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
elif foo == 'spam':
    # this is skipped, even if foo == 'spam' is now true
    foo = 'ham'

Here foo will be set to 'spam'.

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
if foo == 'spam':
    # this is executed when foo == 'bar' as well, as 
    # the previous if statement changed it to 'spam'.
    foo = 'ham'

Now foo is set to 'spam', then to 'ham'.

Technically speaking, elif is part of the (compound) if statement; Python picks the first test in a series of if / elif branches that tests as true, or the else branch (if present) if none are true. Using a separate if statement starts a new selection, independent of the previous if compound statement.

Upvotes: 21

Related Questions