Python 編程中 while 語句用於循環執行程序,即在某條件下,循環執行某段程序,以處理須要重複處理的相同任務。其基本形式爲:python
while 判斷條件: 執行語句……
執行語句能夠是單個語句或語句塊。判斷條件能夠是任何表達式,任何非零、或非空(null)的值均爲true。編程
當判斷條件假false時,循環結束。less
實例:spa
#!/usr/bin/env python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
輸出結果:code
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!
while 語句時還有另外兩個重要的命令 continue,break 來跳過循環,continue 用於跳過該次循環,break 則是用於退出循環,此外"判斷條件"還能夠是個常值,表示循環一定成立,具體用法以下:blog
# continue 和 break 用法 i = 1 while i < 10: i += 1 if i%2 > 0: # 非雙數時跳過輸出 continue print i # 輸出雙數二、4、6、8、10 i = 1 while 1: # 循環條件爲1一定成立 print i # 輸出1~10 i += 1 if i > 10: # 當i大於10時跳出循環 break
在 python 中,while … else 在循環條件爲 false 時執行 else 語句塊:class
實例:循環
#!/usr/bin/python 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