Python while 迴圈
while 迴圈會在條件為 True 時重複執行程式碼,直到條件變成 False。
基本語法
while 條件:
# 條件為 True 時執行的程式碼
count = 0
while count < 5:
print(count)
count += 1
輸出:
0
1
2
3
4
務必確保迴圈最終會結束,否則會造成無窮迴圈:
# 無窮迴圈!不要執行
while True:
print("Forever...")
while 和 for 的選擇
- for 迴圈:當你知道要執行多少次,或要遍歷序列時
- while 迴圈:當你不確定要執行多少次,根據條件決定
# 用 for - 已知執行 5 次
for i in range(5):
print(i)
# 用 while - 不確定執行幾次
import random
num = random.randint(1, 10)
guess = 0
while guess != num:
guess = int(input("Guess a number (1-10): "))
print(f"Correct! The number was {num}")
while...else
while 迴圈可以搭配 else,當條件變成 False 正常結束時執行 else 區塊:
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed")
輸出:
0
1
2
Loop completed
如果迴圈被 break 中斷,else 不會執行:
count = 0
while count < 5:
if count == 3:
break
print(count)
count += 1
else:
print("Loop completed") # 不會執行
輸出:
0
1
2
實際範例
數字猜謎遊戲
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess a number (1-100): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You got it in {attempts} attempts.")
break
計算總和直到輸入 0
total = 0
while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
total += num
print(f"Total: {total}")
等待特定條件
# 模擬等待任務完成
import time
status = "running"
wait_count = 0
while status == "running":
print("Waiting...")
time.sleep(1) # 等待 1 秒
wait_count += 1
if wait_count >= 5:
status = "completed"
print("Task completed!")
驗證使用者輸入
while True:
age = input("Enter your age: ")
if age.isdigit() and int(age) > 0:
age = int(age)
break
else:
print("Please enter a valid positive number.")
print(f"Your age is {age}")
計算數字的位數
num = 12345
count = 0
while num > 0:
num //= 10
count += 1
print(f"Number of digits: {count}") # 5
計算最大公因數 (GCD)
# 使用輾轉相除法
a, b = 48, 18
while b != 0:
a, b = b, a % b
print(f"GCD: {a}") # 6
單行 while(不建議)
技術上可以寫成一行,但不建議這樣寫:
# 不建議
n = 5; fact = 1
while n > 0: fact *= n; n -= 1
print(fact) # 120
# 建議的寫法
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print(fact) # 120