问题描述
我想知道,为什么在你可以这么做时需要使用 elif
?
I was wondering, why is using elif
necessary when you could just do this?
if True:
...
if False:
...
...
推荐答案
当你想确保这个时,你会使用 elif
只挑选一个分支:
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.
与此相比:
foo = 'bar'
spam = 'eggs'
if foo == 'bar':
# do this
if spam == 'eggs':
# *and* do this.
只有 if
语句,选项是非独家。
With just if
statements, the options are not exclusive.
当 if
分支更改程序状态时,这也适用 elif
测试也可能是真的:
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'
此处 foo
将设置为'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'
现在 foo
设置为'spam'
,然后设置为'ham'
。
Now foo
is set to 'spam'
, then to 'ham'
.
从技术上讲, elif
是(复合) if
语句的一部分; Python在一系列中选择第一个测试,如果
/ elif
测试为true的分支,如果没有,则为 else
分支(如果存在)。使用单独的 if
语句启动新选择,独立于之前的 if
复合语句。
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.
这篇关于“if”,“elif”和“elif”。链与普通的“如果”链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!