在Python裡,有所謂的For / While Else語法

不知道是否還有其他的語言有這樣的用法

因為覺得很特別,所以記錄下來

 

這個例子舉例起來比較困難

假如今天要跑一個list,確定裡面的每個項目是否都是水果

用For / While Else表達的意思有點類似說

如果確定裡面的每個項目都是水果,則會進到else

也就是當中沒有因為break而跳脫出迴圈

範例程式碼如下:(改寫自Codecademy學到的例子)

 

fruits = ['banana', 'apple', 'orange', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'carrot':
        print 'A carrot is not a fruit!'
        break
    print f
else:
    print 'All fruits!'

輸出結果為

You have...
banana
apple
orange
pear
grape
All fruits!

但是如果把list改為

fruits = ['banana', 'apple', 'orange', 'pear', 'grape', 'carrot']

則結果為

You have...
banana
apple
orange
pear
grape
A carrot is not a fruit!

則會因為break而不會顯示最後一行「All fruits!」

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 wrijLove 的頭像
    wrijLove

    宅宅情侶的成長日記

    wrijLove 發表在 痞客邦 留言(0) 人氣()