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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…