"if"和"elif"链与简单的"if"链

Eth*_*ein 2 python if-statement

我想知道,为什么elif在你这样做时需要使用?

if True:
    ...
if False:
    ...
...
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 16

elif当您想确保只选择一个分支时,您可以使用它:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
elif spam == 'eggs':
    # won't do this.
Run Code Online (Sandbox Code Playgroud)

比较这个:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
if spam == 'eggs':
    # *and* do this.
Run Code Online (Sandbox Code Playgroud)

只有if声明,选项不是唯一的.

if分支更改程序状态以使elif测试也可能为真时,这也适用:

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
elif foo == 'spam':
    # this is skipped, even if foo == 'spam' is now true
    foo = 'ham'
Run Code Online (Sandbox Code Playgroud)

这里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'
Run Code Online (Sandbox Code Playgroud)

现在foo设置为'spam',然后到'ham'.

从技术上讲,elif是(复合)if陈述的一部分; Python选择测试为true 的一系列/ 分支中的第一个测试,或者如果没有,则选择分支(如果存在).使用单独的语句将启动一个新选择,与前一个复合语句无关.ifelifelseifif