python while 迴圈語句

來源:互聯網
上載者:User

標籤:mat   ted   tin   one   文法   width   lan   nbsp   targe   

Python 編程中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:

while 判斷條件:    執行語句……

執行語句可以是單個語句或語句塊。判斷條件可以是任何錶達式,任何非零、或非空(null)的值均為true。

當判斷條件假false時,迴圈結束。

執行流程圖如下:

Gif 示範 Python while 語句執行過程

執行個體#!/usr/bin/python count = 0 while (count < 9): print ‘The count is:‘, count count = count + 1 print "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 while i < 10: i += 1 if i%2 > 0: # 非雙數時跳過輸出 continue print i # 輸出雙數2、4、6、8、10 i = 1 while 1: # 迴圈條件為1必定成立 print i # 輸出1~10 i += 1 if i > 10: # 當i大於10時跳出迴圈 break

 

無限迴圈

如果條件判斷語句永遠為 true,迴圈將會無限的執行下去,如下執行個體:

執行個體#!/usr/bin/python # -*- coding: UTF-8 -*- var = 1 while var == 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 來中斷迴圈。

 

迴圈使用 else 語句

在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:

執行個體#!/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 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5

 

簡單語句組

類似 if 語句的文法,如果你的 while 迴圈體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

執行個體#!/usr/bin/python flag = 1 while (flag): print ‘Given flag is really true!‘ print "Good bye!"

注意:以上的無限迴圈你可以使用 CTRL+C 來中斷迴圈。

python while 迴圈語句

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.