while
條件循環(huán)的語法格式如下:
while <條件>:
代碼塊
-
while
關(guān)鍵字空格后接條件表達(dá)式末尾加上冒號(hào)組成while
語句 - 代碼塊中的代碼通過4個(gè)空格和
while
語句形成包含關(guān)系
while
條件循環(huán)的運(yùn)行流程圖如下:
1659687665700.png
while
語句首先計(jì)算<條件>
表達(dá)式米罚,如果結(jié)果True
纽什,則執(zhí)行對(duì)應(yīng)代碼塊中的語句,執(zhí)行結(jié)束后再次執(zhí)行<條件>
表達(dá)式巡验,再次判斷結(jié)果恢暖,如果為True
則繼續(xù)執(zhí)行代碼塊中的語句,依此循環(huán),直到<條件>
表達(dá)式為False
時(shí)跳出循環(huán)叉谜,執(zhí)行下一條語句。
注意:當(dāng)<條件>
表達(dá)式恒為True
時(shí)踩萎,形成無限循環(huán)停局,也叫死循環(huán),需要小心使用。
案例代碼
- 打印數(shù)字序列
# 依次打印0-9
>>> i = 0
>>> while i < 10:
... print(i)
... i = i + 1
0
1
2
3
4
5
6
7
8
9
- 循環(huán)序列
通過生成數(shù)字序列作為索引來循環(huán)序列類型
# 列表的循環(huán)
>>> ls = ['a','b','c','d','e','f']
>>> index = 0
>>> while index < len(ls):
... print(ls[index])
... index += 1
a
b
c
d
e
f