首頁  >  文章  >  後端開發  >  Python 循環中的「else」子句!

Python 循環中的「else」子句!

Patricia Arquette
Patricia Arquette原創
2024-10-02 06:09:01991瀏覽

Python

In Python, you can use an else clause not just with if statements, but also with loops (for and while). This might seem strange, but the else block in loops is executed only when the loop completes normally, meaning it doesn't hit a break statement.

Here's an example:

for i in range(5):
    if i == 3:
        break
else:
    print("Loop completed normally")

In this case, since the loop breaks at i == 3, the else clause won't execute. However, if the loop finishes without breaking, the else clause will run.

This little-known feature can be handy for scenarios where you want to check if a loop completed its iteration without interruption.

Oliver | GraphPe | Tutorials

以上是Python 循環中的「else」子句!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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