Python 編程中 while 語句用于循環執行程序,即在某條件下,循環執行某段程序,以處理需要重復處理的相同任務。其基本形式為:
while 判斷條件:
執行語句……
執行語句可以是單個語句或語句塊。判斷條件可以是任何表達式,任何非零、或非空(null)的值均為true。
當判斷條件假false時,循環結束。
執行流程圖如下:

實例:
#!/usr/bin/pythoncount = 0while (count < 9): print 'The count is:', count count = count + 1print "Good bye!"
以上代碼執行輸出結果:
The count is: 0The count is: 1The count is: 2The count is: 3The count is: 4The count is: 5The count is: 6The count is: 7The count is: 8Good bye!
while 語句時還有另外兩個重要的命令 continue,break 來跳過循環,continue 用于跳過該次循環,break 則是用于退出循環,此外"判斷條件"還可以是個常值,表示循環必定成立,具體用法如下:
# continue 和 break 用法i = 1while i < 10: i += 1 if i%2 > 0: # 非雙數時跳過輸出 continue print i # 輸出雙數2、4、6、8、10i = 1while 1: # 循環條件為1必定成立 print i # 輸出1~10 i += 1 if i > 10: # 當i大于10時跳出循環 break;
無限循環
如果條件判斷語句永遠為 true,循環將會無限的執行下去,如下實例:
#!/usr/bin/python# -*- coding: UTF-8 -*-var = 1while var == 1 : # 該條件永遠為true,循環將無限執行下去 num = raw_input("Enter a number :") print "You entered: