真相:

Python break and continue Statements, and else Clauses on Loops

來源:〈迴圈內的 break 和 continue 陳述式及 else 子句
  • if statement 的 else:一旦 if 的條件失效,執行 else 區塊。
  • try statement 的 else:沒有發生 exception,執行 else 區塊。
  • for loop 的 else:裡面沒有被 break,執行 else 區塊。
  • while loop 的 else:一旦 while 的條件失效,執行 else 區塊。

ifwhile 差在哪?

if 只判斷一次後面給的條件,跑過一次就結束 if 區塊往下執行其餘的程式碼;while 會迴圈,只要後面給的條件成立就會一直在 while 迴圈執行,一旦 while 區塊內沒有做好流程控制就可能導致無限迴圈,那就ㄎㄎ了。