国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Python While循環(huán)語句

瀏覽:14日期:2022-08-07 16:19:50

Python 編程中 while 語句用于循環(huán)執(zhí)行程序,即在某條件下,循環(huán)執(zhí)行某段程序,以處理需要重復(fù)處理的相同任務(wù)。其基本形式為:

while 判斷條件: 執(zhí)行語句……

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

當(dāng)判斷條件假false時(shí),循環(huán)結(jié)束。

執(zhí)行流程圖如下:

實(shí)例:

#!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"

以上代碼執(zhí)行輸出結(jié)果:

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 語句時(shí)還有另外兩個(gè)重要的命令 continue,break 來跳過循環(huán),continue 用于跳過該次循環(huán),break 則是用于退出循環(huán),此外"判斷條件"還可以是個(gè)常值,表示循環(huán)必定成立,具體用法如下:

# continue 和 break 用法 i = 1 while i < 10:i += 1 if i%2 > 0: # 非雙數(shù)時(shí)跳過輸出 continue print i # 輸出雙數(shù)2、4、6、8、10 i = 1 while 1: # 循環(huán)條件為1必定成立 print i # 輸出1~10 i += 1 if i > 10: # 當(dāng)i大于10時(shí)跳出循環(huán) break 無限循環(huán)

如果條件判斷語句永遠(yuǎn)為 true,循環(huán)將會(huì)無限的執(zhí)行下去,如下實(shí)例:

#!/usr/bin/python # -*- coding: UTF-8 -*- var = 1 while var == 1 : # 該條件永遠(yuǎn)為true,循環(huán)將無限執(zhí)行下去 num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"

以上實(shí)例輸出結(jié)果:

Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number between :Traceback (most recent call last): File "test.py", line 5, in <module> num = raw_input("Enter a number :") KeyboardInterrupt

注意:以上的無限循環(huán)你可以使用 CTRL+C 來中斷循環(huán)。

循環(huán)使用 else 語句

在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區(qū)別,else 中的語句會(huì)在循環(huán)正常執(zhí)行完(即 for 不是通過 break 跳出而中斷的)的情況下執(zhí)行,while … 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"

以上實(shí)例輸出結(jié)果為:

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循環(huán)體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

#!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"

注意:以上的無限循環(huán)你可以使用 CTRL+C 來中斷循環(huán)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 咸宁市| 大安市| 新乡县| 文登市| 黄大仙区| 庆阳市| 鹰潭市| 宜丰县| 乐业县| 海伦市| 新河县| 竹北市| 林芝县| 政和县| 视频| 潮州市| 尖扎县| 新余市| 临泽县| 陈巴尔虎旗| 文成县| 綦江县| 鲁甸县| 喀什市| 襄汾县| 巴里| 大余县| 崇左市| 靖安县| 霸州市| 和田县| 三门县| 乌海市| 灵宝市| 竹溪县| 开阳县| 台中县| 林芝县| 萨迦县| 土默特左旗| 霞浦县|