Python - while迴圈



Python while 迴圈

在 Python 程式語言中,while 迴圈會重複執行目標語句,直到指定的布林表示式為假。此迴圈以while 關鍵字開頭,後跟布林表示式和冒號符號 (:)。然後,縮排的語句塊開始。

此處,語句可以是單個語句或具有統一縮排的語句塊。條件可以是任何表示式,真值為任何非零值。一旦表示式變為假,程式控制就會轉移到迴圈後緊跟的行。

如果它未能變為假,迴圈將繼續執行,除非強制停止否則不會停止。這種迴圈稱為無限迴圈,在計算機程式中是不希望看到的。

while 迴圈的語法

Python 程式語言中 while 迴圈的語法如下:

while expression:
   statement(s)

Python中,所有在程式設計結構之後以相同數量的字元空格縮排的語句都被視為單個程式碼塊的一部分。Python 使用縮排作為其語句分組的方法。

while 迴圈的流程圖

下圖說明了 while 迴圈:

while loop

示例 1

以下示例說明了 while 迴圈的工作原理。此處,迭代執行直到 count 的值變為 5。

count=0
while count<5:
   count+=1
   print ("Iteration no. {}".format(count))

print ("End of while loop")

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

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
End of while loop

示例 2

這是一個使用while迴圈的另一個例子。每次迭代,程式都會請求使用者輸入,並持續重複,直到使用者輸入一個非數字字串。isnumeric()函式如果輸入是整數則返回true,否則返回false。

var = '0'
while var.isnumeric() == True:
   var = "test"
   if var.isnumeric() == True:
      print ("Your input", var)
print ("End of while loop")

執行程式碼後,將產生以下輸出:

enter a number..10
Your input 10
enter a number..100
Your input 100
enter a number..543
Your input 543
enter a number..qwer
End of while loop

Python無限while迴圈

如果條件永遠不會變成FALSE,迴圈就會變成無限迴圈。使用while迴圈時必須謹慎,因為此條件可能永遠不會解析為FALSE值。這將導致一個永不結束的迴圈。這樣的迴圈稱為無限迴圈。

無限迴圈可能在客戶端/伺服器程式設計中很有用,其中伺服器需要持續執行,以便客戶端程式可以根據需要與之通訊。

示例

讓我們來看一個例子,瞭解Python中的無限迴圈是如何工作的:

var = 1
while var == 1 : # This constructs an infinite loop
   num = int(input("Enter a number :"))
   print ("You entered: ", num)
print ("Good bye!")

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

Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
   File "examples\test.py", line 5, in
      num = int(input("Enter a number :"))
KeyboardInterrupt
上面的例子進入無限迴圈,您需要使用CTRL+C來退出程式。

Python while-else迴圈

Python支援將else語句while迴圈關聯起來。如果else語句while迴圈一起使用,則當條件在控制轉移到主執行行之前變為false時,將執行else語句

帶有else語句的While迴圈流程圖

下面的流程圖顯示瞭如何將else語句while迴圈一起使用:

output hello world

示例

下面的例子說明了else語句與while語句的組合。只要計數小於5,就會列印迭代計數。當它變成5時,else塊中的print語句會在控制傳遞到主程式中的下一條語句之前執行。

count=0
while count<5:
   count+=1
   print ("Iteration no. {}".format(count))
else:
   print ("While loop over. Now in else block")
print ("End of while loop")

執行上面的程式碼後,它將列印以下輸出:

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

單語句塊

類似於if語句語法,如果您的while子句只包含一個語句,則可以將其放在與while標題相同的行上。

示例

以下示例顯示瞭如何使用單行while子句。

flag = 0
while (flag): print ("Given flag is really true!")
print ("Good bye!")

執行此程式碼時,它將顯示以下輸出:

Good bye!

將標誌值更改為“1”並嘗試上述程式。如果您這樣做,它將進入無限迴圈,您需要按CTRL+C鍵退出。

廣告