[Python] Loop 配合 else 的妙用
Python 算是用了滿久了,居然現在才發現這個神奇的用法。
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
也就是說 Python 中 for
以及 while
可以像 if
一樣有個 else
區塊,當迴圈沒有中斷就會執行到 else
區塊。
換句話說,就是 esle
為 for loop
的其中一個部份,如果 break
就一併跳出,沒有的話就會執行到。
nums = [60, 70, 30, 110, 90]
found = False
for n in nums:
if n > 100:
found = True
print "There is a number bigger than 100"
break
if not found:
print "Not found!"
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print "There is a number bigger than 100"
break
else:
print "Not found!"
如此一來,透過使用 else
可以節省一些 flag 的使用。