Python 程式設計中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:
while 判斷條件(condition):
執行語句(statements)……
執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零、或非空(null)的值均為true。
當判斷條件假 false 時,迴圈結束。
Python中的while迴圈執行流程圖如下:
while迴圈也稱為預測試迴圈。
通常,只要while中給定的條件為真,while迴圈就允許執行部分程式碼。
while迴圈判斷與if相似。
while迴圈主要用於事先不知道迭代次數的情況。
Python中國while迴圈的語法如下:
while expression:
statements
這裡,語句可以是單個語句或語句組。表示式應該是任何有效的python表示式,結果為true或false。true是任何非零值。
例
i=1;
while i<=10:
print(i);
i=i+1;
輸出:
1
2
3
4
5
6
7
8
9
10
例
i=1
number=0
b=9
number = int(input(“輸入數字?”))
while i<=10:
print(“%d X %d = %d \n”%(number,i,number*i));
i = i+1;
輸出:
輸入數字?10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
無限迴圈
如果while迴圈中給出的條件永遠不會變為false,則while迴圈將永遠不會終止並導致無限while迴圈。
while迴圈中的任何非零值表示始終為真的條件,而0表示始終為false的條件。如果我們希望程式在迴圈中連續執行而沒有任何干擾,這種方法很有用。
例
while (1):
print(“Hi! we are inside the infinite while loop”);
輸出:
Hi! we are inside the infinite while loop
(無限迴圈)
例
var = 1
while var != 2:
i = int(input(“Enter the number?”))
print (“Entered value is %d”%(i))
輸出:
Enter the number?102
Entered value is 102
Enter the number?102
Entered value is 102
Enter the number?103
Entered value is 103
Enter the number?103
(無限迴圈)
在迴圈中使用帶有Python的else
Python使我們也可以使用while迴圈和while迴圈。
當while語句中給出的條件變為false時,執行else塊。
與for迴圈類似,如果使用break語句斷開while迴圈,則不會執行else塊,並且將執行else塊之後的語句。
請看以下示例:
i=1;
while i<=5:
print(i)
i=i+1;
else:print(“The while loop exhausted”);
輸出:
1
2
3
4
5
The while loop exhausted
例
i=1;
while i<=5:
print(i)
i=i+1;
if(i==3):
break;
else:print(“The while loop exhausted”);
輸出:
1
2
以上即為Python迴圈型別中的while迴圈的相關介紹,同學們認真閱讀學習,如有問題可下方留言諮詢,將第一時間為大家解決。