while expression: statement(s)
在這里,語句(statement(s))可以是單個語句或均勻縮進語句塊。條件(condition)可以是表達式,以及任何非零值時為真。當(dāng)條件為真時循環(huán)迭代。
在Python中,所有編程結(jié)構(gòu)后相同數(shù)量的字符空格的縮進語句被認(rèn)為是一個單一代碼塊的一部分。Python使用縮進作為分組語句的方法。

在這里,while循環(huán)的關(guān)鍵點是循環(huán)可能永遠不會運行。當(dāng)條件測試,結(jié)果是false,將跳過循環(huán)體并執(zhí)行while循環(huán)之后的第一個語句。
#!/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!
塊在這里,其中包括打印和增量語句,重復(fù)執(zhí)行直到計數(shù)(count)不再小于9。每次迭代,將顯示索引計數(shù)(count)的當(dāng)前值和然后count 加1。
如果條件永遠不會變?yōu)镕ALSE,一個循環(huán)就會變成無限循環(huán)。使用while循環(huán)時,有可能永遠不會解析為FALSE值時而導(dǎo)致無限循環(huán),所以必須謹(jǐn)慎使用。導(dǎo)致無法結(jié)束一個循環(huán)。這種循環(huán)被稱為一個無限循環(huán)。
服務(wù)器需要連續(xù)運行,以便客戶端程序可以在有需要通信時與服務(wù)器端通信,所以無限循環(huán)在客戶機/服務(wù)器編程有用。
#!/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
如果else語句在一個for循環(huán)中使用,當(dāng)循環(huán)已經(jīng)完成(用盡時)迭代列表執(zhí)行else語句。
如果else語句用在while循環(huán)中,當(dāng)條件變?yōu)?nbsp;false,則執(zhí)行 else 語句。
下面的例子說明了,只要它小于5,while語句打印這些數(shù)值,否則else語句被執(zhí)行。
#!/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 同行整個標(biāo)題。
#!/usr/bin/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")