這篇文章主要講解了“Python中for循環(huán)和while循環(huán)有什么不同”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Python中for循環(huán)和while循環(huán)有什么不同”吧!
Python中用while語句和for語句表示循環(huán)執(zhí)行某一段代碼
while后面跟一個條件,或者跟一個序列(列表、元組等),序列為空則跳出循環(huán),否則繼續(xù)循環(huán)
for循環(huán)后面跟一個序列,循環(huán)次數(shù)為序列的長度
while循環(huán)可以加個else語句,跳出while的時候就執(zhí)行這個else
舉例
a = 3
while a > 0:
print(a)
a -= 1
1
2
3
4
輸出:
3
2
1
shoplist = ['apple', 'mango', 'carrot', 'banana']
while shoplist:
print(3)
1
2
3
輸出:一直輸出3,直到按ctrl+c
shoplist = ['apple', 'mango', 'carrot', 'banana']
while shoplist:
print(3)
shoplist = shoplist[:(len(shoplist)-1)]#每次循環(huán)都去掉最后一個元素
1
2
3
4
輸出:
3
3
3
3
shoplist = ['apple', 'mango', 'carrot', 'banana']
while shoplist:
print(3)
shoplist = shoplist[:(len(shoplist)-1)]
else:
print('finished')#else語句
1
2
3
4
5
6
輸出:
3
3
3
3
finished
shoplist = ['apple', 'mango', 'carrot', 'banana']
for i in shoplist:
print(i) #這里面i會被逐次賦值為shoplist里面的元素
1
2
3
輸出:
apple
mango
carrot
banana
shoplist = ('apple', 'mango', 'carrot', 'banana')
for i in shoplist:
print(i) #這里shoplist是元組,for循環(huán)也可以跟元組
1
2
3
輸出:
apple
mango
carrot
banana
感謝各位的閱讀,以上就是“Python中for循環(huán)和while循環(huán)有什么不同”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Python中for循環(huán)和while循環(huán)有什么不同這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
標(biāo)題名稱:Python中for循環(huán)和while循環(huán)有什么不同-創(chuàng)新互聯(lián)
新聞來源:http://www.chinadenli.net/article30/dhejpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、定制開發(fā)、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、全網(wǎng)營銷推廣、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容