有的時候,一個 if … else … 還不夠用。比如,根據年齡的劃分:
條件1:18歲或以上:adult
條件2:6歲或以上:teenager
條件3:6歲以下:kid
Python if-elif-else知識點
if age >= 18: print 'adult'else: if age >= 6: print 'teenager' else: print 'kid'
這樣寫出來,我們就得到了一個兩層嵌套的 if … else … 語句。這個邏輯沒有問題,但是,如果繼續增加條件,比如3歲以下是 baby:
if age >= 18: print 'adult'else: if age >= 6: print 'teenager' else: if age >= 3: print 'kid' else: print 'baby'
這種縮進只會越來越多,代碼也會越來越難看。
要避免嵌套結構的 if … else …,我們可以用 if … 多個elif … else … 的結構,一次寫完所有的規則:
if age >= 18: print 'adult'elif age >= 6: print 'teenager'elif age >= 3: print 'kid'else: print 'baby'
elif 意思就是 else if。這樣一來,我們就寫出了結構非常清晰的一系列條件判斷。
特別注意: 這一系列條件判斷會從上到下依次判斷,如果某個判斷為 True,執行完對應的代碼塊,后面的條件判斷就直接忽略,不再執行了。
請思考下面的代碼:
age = 8if age >= 6: print 'teenager'elif age >= 18: print 'adult'else: print 'kid'
當 age = 8 時,結果正確,但 age = 20 時,為什么沒有打印出 adult?
如果要修復,應該如何修復?
任務
如果按照分數劃定結果:
90分或以上:excellent
80分或以上:good
60分或以上:passed
60分以下:failed
請編寫程序根據分數打印結果。
答案
score = 85
if score >= 90:
print 'excellent'
elif score >= 80:
print 'good'
elif score >= 60:
print 'passed'
else :
print 'failed'
新聞熱點
疑難解答