在Python中,循環是一種控制結構,用于重復執行一段代碼。有兩種主要的循環類型:for循環和while循環。以下是關于如何使用這兩種循環的簡要說明和示例。
for variable in sequence:
# 代碼塊
示例:
# 遍歷列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 輸出:
# apple
# banana
# cherry
while condition:
# 代碼塊
示例:
count = 0
while count < 5:
print(count)
count += 1
# 輸出:
# 0
# 1
# 2
# 3
# 4
在使用循環時,還有一些有用的技巧:
range()
函數生成一個序列,以便在for循環中使用。例如,要生成一個0到4的整數序列,可以使用range(5)
。for i in range(5):
print(i)
# 輸出:
# 0
# 1
# 2
# 3
# 4
break
和continue
語句來提前退出循環或跳過當前迭代。break
用于完全退出循環,而continue
用于跳過當前迭代并繼續執行下一次迭代。for i in range(5):
if i == 3:
break
print(i)
# 輸出:
# 0
# 1
# 2
for i in range(5):
if i == 3:
continue
print(i)
# 輸出:
# 0
# 1
# 2
# 4
else
子句,當循環正常結束時(沒有遇到break
),將執行else
子句中的代碼。for i in range(5):
if i == 3:
print("Found 3")
break
else:
print("Not found 3")
# 輸出:
# Found 3