Python while循環基礎與實踐
1. while循環基本語法
# 基本while循環
count = 0
while count < 5:
print(count)
count += 1 # 別忘了更新條件
# 使用break退出循環
number = 0
while True:
if number >= 5:
break
print(number)
number += 1
注意事項:
- 必須在循環內更新條件,否則可能造成無限循環
- 確保循環條件最終會變為False
- 可以使用break強制退出循環
2. 實際應用範例
猜數字遊戲
import random
target = random.randint(1, 100)
guess_count = 0
while True:
guess = int(input("猜一個1-100的數字:"))
guess_count += 1
if guess == target:
print(f"恭喜猜對了!共猜了{guess_count}次")
break
elif guess < target:
print("太小了,再試試")
else:
print("太大了,再試試")
密碼驗證
correct_password = "python123"
max_attempts = 3
attempts = 0
while attempts < max_attempts:
password = input("請輸入密碼:")
if password == correct_password:
print("登入成功!")
break
attempts += 1
remaining = max_attempts - attempts
print(f"密碼錯誤,還有{remaining}次機會")
3. while與else的組合
# 當while循環正常結束時執行else
count = 0
while count < 3:
print(count)
count += 1
else:
print("循環正常結束")
# break會跳過else
count = 0
while count < 3:
if count == 2:
break
print(count)
count += 1
else:
print("這句不會執行")
4. 常見陷阱和解決方案
無限循環
# 錯誤示例
while count < 5:
print(count)
# 忘記更新count
# 正確示例
while count < 5:
print(count)
count += 1
輸入驗證
# 確保輸入有效數字
while True:
try:
age = int(input("請輸入年齡:"))
if 0 <= age <= 120:
break
print("請輸入有效年齡(0-120)")
except ValueError:
print("請輸入數字")
5. 練習題
-
實現一個計算器程序:
- 循環接受用戶輸入兩個數字和運算符
- 輸入’q’退出程序
- 處理除數為零的情況
-
實現ATM程序:
- 初始餘額1000元
- 可以選擇存款、取款、查詢餘額
- 輸入’q’退出程序
- 確保輸入金額為正數