"如果"," elif"连锁与平原"如果"链

时间:2014-04-22 20:57:18

标签: python if-statement

我在想,为什么在你可以这样做的时候使用elif呢?

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

2 个答案:

答案 0 :(得分:16)

如果您想确保只挑选一个分支,则可以使用elif

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语句,选项不是独占的。

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'

此处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'

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

答案 1 :(得分:2)

itertools.count是一个生成器,每次调用它时都会为您提供一个新值,因此它可用于说明此类事物。

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

elif的最后一个值必须为6才能与if相同。但是生成器也可以用完了#34;这意味着你需要能够避免两次检查它们。

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

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