Python循環語句——while循環

while循環

while 判斷條件(condition):
    執行語句(statements)……

while循環之前,先判斷一次,如果滿足條件的話,再循環
在給定的判斷條件為 true 時執行循環體,否則退出循環體。

3個條件:
初始值
條件表達式
變量的自增

count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1
print ("Good bye!")
"""
#運行結果
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!
"""

continue和break

while 語句時還有另外兩個重要的命令 continue,break 來跳過循環,continue 用于跳過該次循環,break 則是用于退出循環,此外"判斷條件"還可以是個常值,表示循環必定成立

continue

如果使用 continue 語句,可以停止當前的迭代,并繼續下一個:


i = 0
while i < 7:
    i += 1 
    if i == 3: 
        continue  #如果 i 等于 3,則繼續下一個迭代(跳過循環):
    print(i)

"""
運行的結果是
1
2
4
5
6
7
"""

break

如果使用 break 語句,即使 while 條件為真,我們也可以停止循環:


i = 1
while i < 7:
    print(i)
    if i == 3:
        break  #在 i 等于 3 時退出循環(跳出循環):
    i += 1
"""
運行的結果是
1
2
3
"""
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。