如何在 Python 中使用 for 迴圈中的 else 條件語句?
迴圈(for 和 while)中的 else 塊在迴圈的所有迭代完成後並在程式流退出迴圈體之前執行。語法如下 −
語法
while expr==True: #statements to be iterated while expr is true. else: #this statement(s) will be executed afteriterations are over
# 退出迴圈體後將執行此操作
示例
for x in range(6):
print (x)
else:
print ("else block of loop")
print ("loop is over")輸出
輸出如下所示 −
0 1 2 3 4 5 else block of loop loop is over
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP