首頁 >後端開發 >Python教學 >你所不知道的python 循環中的else

你所不知道的python 循環中的else

高洛峰
高洛峰原創
2016-10-19 15:16:371185瀏覽

眾多語言中都有if else這對條件選擇組合,但是在python中還有更多else使用的地方,比如說循環for,或者while都可以和else組合。

下面簡單介紹一下for-else while-else組合

循環組合中的else執行的情況下是循環正常結束(即不是使用break退出)。如下列程式碼:

numbers = [1,2,3,4,5]
for n in numbers:
    if (n > 5):
        print('the value is %d '%(n))
        break
else:
    print('the for loop does not end with break')
     
i = 0
while(numbers[i] < 5):
    print(&#39;the index %d value is %d&#39;%(i, numbers[i]))
    if (numbers[i] < 0) :
        break
    i = i + 1
else:
    print(&#39;the loop does not end with break&#39;)
   
numbers = [1,2,3,4,5]
for n in numbers:
    if (n > 5):
        print(&#39;the value is %d &#39;%(n))
        break
else:
    print(&#39;the for loop does not end with break&#39;)
    
i = 0
while(numbers[i] < 5):
    print(&#39;the index %d value is %d&#39;%(i, numbers[i]))
    if (numbers[i] < 0) :
        break
    i = i + 1
else:
    print(&#39;the loop does not end with break&#39;)

執行結果如下:

C:\Python27>python.exe for_else.py
the for loop does not end with break
the index 0 value is 1
the index 1 value is 2
the index 2 value is 3
the index 3 value is 4
the loop does not end with break


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn