Python for-else 迴圈



Python - For Else 迴圈

Python 支援將一個可選的else 塊for 迴圈關聯。如果else 塊for 迴圈一起使用,則只有當 for 迴圈正常終止時才會執行它。

當 for 迴圈在沒有遇到break 語句的情況下完成所有迭代時,for 迴圈會正常終止,這允許我們在滿足特定條件時退出迴圈。

For Else 迴圈流程圖

下面的流程圖說明了for-else 迴圈的使用:

for-else

For Else 迴圈語法

以下是帶可選 else 塊的 for 迴圈的語法:

for variable_name in iterable:
 #stmts in the loop
 .
 .
 .
else:
 #stmts in else clause
 .
 .

For Else 迴圈示例

以下示例說明了在Python中將 else 語句與 for 語句結合使用的情況。在計數小於 5 之前,會列印迭代計數。當它變為 5 時,else 塊中的 print 語句會在控制權傳遞到主程式中的下一條語句之前執行。

for count in range(6):
   print ("Iteration no. {}".format(count))
else:
   print ("for loop over. Now in else block")
print ("End of for loop")

執行此程式碼將產生以下輸出

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
for loop over. Now in else block
End of for loop

不帶 break 語句的 For-Else 結構

如本教程前面所述,else 塊僅在迴圈正常終止時(即不使用 break 語句)才會執行。

示例

在下面的程式中,我們使用不帶 break 語句的 for-else 迴圈。

for i in ['T','P']:
   print(i)
else:
   # Loop else statement
   # there is no break statement in for loop, hence else part gets executed directly
   print("ForLoop-else statement successfully executed")

執行上述程式將生成以下輸出:

T
P
ForLoop-else statement successfully executed

帶 break 語句的 For-Else 結構

如果迴圈被強制終止(使用break語句),直譯器會忽略else語句,因此會跳過它的執行。

示例

以下程式演示了else條件在break語句中的工作方式。

for i in ['T','P']:
   print(i)
   break
else:
   # Loop else statement
   # terminated after 1st iteration due to break statement in for loop
   print("Loop-else statement successfully executed")

執行上述程式將生成以下輸出:

T

帶break語句和if條件的For-Else

如果我們將for-else結構與break語句if條件一起使用,for迴圈將遍歷迭代器,並且在這個迴圈中,可以使用if塊來檢查特定條件。如果迴圈在不遇到break語句的情況下完成,則執行else塊中的程式碼。

示例

以下程式演示了else條件在break語句和條件語句中的工作方式。

# creating a function to check whether the list item is a positive
# or a negative number
def positive_or_negative():
   # traversing in a list
   for i in [5,6,7]:
   # checking whether the list element is greater than 0
      if i>=0:
         # printing positive number if it is greater than or equal to 0
         print ("Positive number")
      else:
         # Else printing Negative number and breaking the loop
         print ("Negative number")
         break
   # Else statement of the for loop
   else:
      # Statement inside the else block
      print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()

執行上述程式將生成以下輸出:

Positive number
Positive number
Positive number
Loop-else Executed
廣告