Python break和continue的使用時機
1. break的適用場景
1.1 提前退出循環
# 找到第一個符合條件的值就退出
numbers = [4, 7, 2, 9, 1, 5]
target = 9
for num in numbers:
if num == target:
print(f"找到目標數字:{target}")
break
1.2 輸入驗證
# 直到輸入正確才退出循環
while True:
password = input("請輸入密碼:")
if len(password) >= 6:
print("密碼設置成功")
break
print("密碼太短,請重新輸入")
2. continue的適用場景
2.1 跳過特定條件
# 只處理偶數
for num in range(10):
if num % 2 != 0:
continue
print(f"處理偶數:{num}")
2.2 數據過濾
# 過濾無效數據
data = ["apple", "", "banana", None, "orange", ""]
for item in data:
if not item: # 跳過空值
continue
print(f"處理數據:{item}")
3. 使用建議
避免過度使用
- 不要在一個循環中使用過多的break或continue
- 優先考慮使用條件判斷來控制流程
- 保持代碼的可讀性和維護性
4. 練習題
-
實現一個簡單的購物車程序:
- 循環輸入商品名稱和價格
- 輸入’q’時退出
- 跳過價格為0的商品
- 最後顯示總金額
-
實現一個數字猜謎遊戲:
- 生成1-100的隨機數
- 最多猜10次
- 猜對時使用break退出
- 輸入非數字時使用continue跳過