循環是編程的重要組成部分。
在Python中,我們有2種循環:while循環和for循環。
while
循環
while
循環是使用while
關鍵字,然後重複執行其塊,直到條件被評估為False
:
condition = True
while condition == True:
print("The condition is True")
這是一無限循環。永無止境。
讓我們在第一次迭代後立即停止循環:
condition = True
while condition == True:
print("The condition is True")
condition = False
print(“After the loop”)
在這種情況下,運行第一次迭代,因為條件測試被評估為True
,並且在第二次迭代中,條件測試的計算結果為False
,因此控制將在循環後轉到下一條指令。
通常有一個計數器在一定數量的周期後停止迭代:
count = 0
while count < 10:
print("The condition is True")
count = count + 1
print(“After the loop”)
for
循環
使用for
循環,我們可以告訴Python在預先確定的時間內執行一個塊,而無需單獨的變量並且有條件地檢查其值。
例如,我們可以迭代列表中的項目:
items = [1, 2, 3, 4]
for item in items:
print(item)
或者,您可以使用range()
功能:
for item in range(04):
print(item)
range(4)
創建一個從0開始並包含4個項目的序列:[0, 1, 2, 3]
。
要獲取索引,您應該將序列包裝到enumerate()
功能:
items = [1, 2, 3, 4]
for index, item in enumerate(items):
print(index, item)
打破並繼續
兩個都while
和for
可以使用兩個特殊關鍵字在塊內中斷循環:break
和continue
。
continue
停止當前迭代,並告訴Python執行下一個迭代。
break
完全停止循環,並在循環結束後繼續執行下一條指令。
這裡的第一個示例打印1, 3, 4
。第二個示例打印1
:
items = [1, 2, 3, 4]
for item in items:
if item == 2:
continue
print(item)
items = [1, 2, 3, 4]
for item in items:
if item == 2:
break
print(item)
更多python教程:
- Python簡介
- 在macOS上安裝Python 3
- 運行Python程序
- Python 2和Python 3
- 使用Python的基礎
- Python數據類型
- Python運算子
- Python字符串
- Python布爾值
- Python數字
- Python,接受輸入
- Python控制語句
- Python列表
- Python元組
- Python集
- Python字典
- Python函數
- Python對象
- Python循環
- Python模塊
- Python類
- Python標準庫
- 調試Python
- Python變量範圍
- Python,從命令行接受參數
- Python遞歸
- Python嵌套函數
- Python Lambda函數
- Python閉包
- Python虛擬環境
- 使用Python將GoPro用作遠程網絡攝像頭
- Python,如何從字符串創建列表
- Python裝飾器
- Python Docstrings
- Python自省
- Python註釋
- Python,如何列出目錄中的文件和文件夾
- Python,如何檢查數字是否為奇數或偶數
- Python,如何獲取文件的詳細信息
- Python,如何檢查文件或目錄是否存在
- Python異常
- Python,如何創建目錄
- Python,如何創建一個空文件
- Python,`with`語句
- Python,創建網絡請求
- Python,使用`pip`安裝第三方軟件包
- Python,讀取文件內容