python2.7入門---迴圈語句(while)
Python提供了for迴圈和while迴圈(在Python中沒有do..while迴圈),我們通過表單看一下:
迴圈型別 | 描述 |
---|---|
在給定的判斷條件為 true 時執行迴圈體,否則退出迴圈體。 | |
for 迴圈 | 重複執行語句 |
巢狀迴圈 | 你可以在while迴圈體中巢狀for迴圈 |
然後呢,咱們也瞭解,迴圈控制語句可以更改語句執行的順序,那麼就來了解一下,Python支援的迴圈控制語句:
控制語句 | 描述 |
---|---|
在語句塊執行過程中終止迴圈,並且跳出整個迴圈 | |
在語句塊執行過程中終止當前迴圈,跳出該次迴圈,執行下一次迴圈。 | |
pass是空語句,是為了保持程式結構的完整性。 |
咱們首先就來看一下,while迴圈語句。Python 程式設計中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:
while判斷條件:執行語句……
執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零、或非空(null)的值均為true。當判斷條件假false時,迴圈結束。我們來看一下執行流程圖:
咱們再來看一個,Gif演示的python的while執行流程圖:
可能演示不了,呵呵,那就算了,咱們直接來看例項:
#!/usr/bin/python count = 0 while(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 = 1 whilei < 10: i += 1 ifi%2 > 0:# 非雙數時跳過輸出 continue printi# 輸出雙數2、4、6、8、10 i = 1 while1: # 迴圈條件為1必定成立 printi# 輸出1~10 i += 1 ifi > 10: # 當i大於10時跳出迴圈 break
我們要知道,如果條件判斷語句永遠為 true,迴圈將會無限的執行下去:
#!/usr/bin/python # -*- coding: UTF-8 -*-var = 1 whilevar == 1 : # 該條件永遠為true,迴圈將無限執行下去 num = raw_input("Enter a number :") print"You entered: ", num print"Good bye!"
以上例項輸出結果:
Enter a number :20You entered:20Enter a number :29You entered:29Enter a number :3You entered:3Enter a number between :Traceback(most recent call last):File"test.py", line 5,in<module> num = raw_input("Enter a number :")KeyboardInterrupt
注意:以上的無限迴圈你可以使用 CTRL+C 來中斷迴圈。
那麼,在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:
#!/usr/bin/python count = 0 whilecount < 5: printcount, " is less than 5" count = count + 1 else: printcount, " is not less than 5"
以上例項輸出結果為:
0is less than 51is less than 52is less than 53is less than 54is less than 55isnot less than 5
接下來我們來看一下,簡單的語句組。類似 if 語句的語法,如果你的 while 迴圈體中只有一條語句,你可以將該語句與while寫在同一行中,如下所示:
#!/usr/bin/python flag = 1while(flag): print'Given flag is really true!' print"Good bye!"
注意:以上的無限迴圈你可以使用 CTRL+C 來中斷迴圈。
好啦,關於while的分享到這裡就差不多結束了,感謝各位鑑賞,如果感覺不錯,請多多點贊支援哦。。。