溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python中while的使用方法

發(fā)布時(shí)間:2020-08-24 14:06:20 來源:億速云 閱讀:389 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)python中while的使用方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

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

其基本形式為:

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

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

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

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

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

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

在 python 中,while … else 在循環(huán)條件為 false 時(shí)執(zhí)行 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

關(guān)于python中while的使用方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI