Python3 while迴圈語句

Python編程語言中的 while 迴圈語句只要給定條件為真,則會重複執行的目標聲明或語句。

語法

Python編程語言的 while迴圈的語法 -
while expression:
   statement(s) 

在這裏,語句(statement(s))可以是單個語句或均勻縮進語句塊。條件(condition)可以是運算式,以及任何非零值時為真。當條件為真時迴圈迭代。

當條件為false,則程式控制流會進到緊接在迴圈之後的行。

在Python中,所有編程結構後相同數量的字元空格的縮進語句被認為是一個單一代碼塊的一部分。Python使用縮進作為分組語句的方法。

流程圖


在這裏,while迴圈的關鍵點是迴圈可能永遠不會運行。當條件測試,結果是false,將跳過循環體並執行while迴圈之後的第一個語句。

示例

#!/usr/bin/python3

count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1

print ("Good bye!")
當執行上面的代碼,它產生以下結果 -
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye! 

塊在這裏,其中包括列印和增量語句,重複執行直到計數(count)不再小於9。每次迭代,將顯示索引計數(count)的當前值和然後count 加1。

無限迴圈

如果條件永遠不會變為FALSE,一個迴圈就會變成無限迴圈。使用while迴圈時,有可能永遠不會解析為FALSE值時而導致無限迴圈,所以必須謹慎使用。導致無法結束一個迴圈。這種迴圈被稱為一個無限迴圈。

伺服器需要連續運行,以便客戶端程式可以在有需要通信時與伺服器端通信,所以無限迴圈在客戶機/伺服器編程有用。

#!/usr/bin/python3

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才能退出程式。

迴圈使用else語句

Python支持迴圈語句相關的else語句。
  • 如果else語句在一個for迴圈中使用,當迴圈已經完成(用盡時)迭代列表執行else語句。

  • 如果else語句用在while迴圈中,當條件變為 false,則執行 else 語句。

下麵的例子說明了,只要它小於5,while語句列印這些數值,否則else語句被執行。

#!/usr/bin/python3

count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")
當執行上面的代碼,它產生以下結果 -
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

單套件聲明

類似於if語句的語法,如果while子句僅由單個語句組成, 它可以被放置在與while 同行整個標題。

這裏是一個單行的 while 子句的語法和例子 -
#!/usr/bin/python3

flag = 1

while (flag): print ('Given flag is really true!')

print ("Good bye!")
上面的例子中進入無限迴圈,需要按 Ctrl+C 鍵才能退出。

上一篇: Python3決策 下一篇: Python3 for迴圈語句