2014-04-22 29 views

回答

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聲明的一部分;蟒挑選在一系列if/elif分支,測試爲真,或else分支第一試驗(如果存在的話),如果沒有爲真。使用單獨的if語句開始一個新的選擇,獨立於之前的if複合語句。

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 

的最後一個值必須是6爲elif是相同if。但發電機也可能會「用完」,這意味着您需要能夠避免兩次檢查它們。

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!