TUTORIAL · Python

Python while 迴圈

Python 3 基礎教程 - Python While 迴圈

本頁內容

在本節中,我們來介紹 while 迴圈,該迴圈內的語句會被執行多次,直到迴圈判斷條件不為 True 為止。在一個 while 迴圈中,如果判斷條件是 True,則執行 while 內部語句,這個過程一直持續到條件變為 False。

while 跟 for 迴圈相比,主要使用在當你不知道將要執行多少次迴圈語句(迭代總數)時。

以下是 Python while 迴圈的語法:

while condition:
    block of statements

這裡,如果 condition 是 True 的話,則控制進入主體 while 並執行內部語句塊,當條件變為時 False,迭代將停止並且迴圈也會終止。

while 迴圈示例

以下程式示例用來計算前五個偶數的總和:

sum = 0
i = 0  # initializing counter variable at 0
while i <= 10:
    sum = sum + i
    i = i + 2  # incrementing counter variable with inter of 2 for even numbers
print("Sum of first five even numbers =", sum)
Sum of first five even numbers = 30

首先,需要初始化計數器變數的值 i,然後 while 的判斷條件是如果 i 大於 10 則應該終止 while 迴圈。然後 i 在每次迭代中遞增 2 來增加計數器變數,這將生成偶數序列,因為最初 i 為零。

當 i 變為 12 時,迴圈終止並將 sum 列印出來。在迴圈的每次迭代中,將值 i 累加到 sum。

while 迴圈結合 else

在 while 迴圈語法中,你也可以在後面新增 else 語句塊,改語句塊在條件判斷為 False 並且迴圈沒有被跳出情況下被執行。

Note
如果你使用 break 終止 while 迴圈,那它將忽略該 else 部分。
count = 0
while count < 4:
    print("You are inside while loop")
    count = count + 1
else:
    print("You are in else part")
You are inside while loop
You are inside while loop
You are inside while loop
You are inside while loop
You are in else part

當 count 大於 4 時,else 部分會被執行。