Python 中的 while 循環控制結構深度解析與 15 個實踐案例
在 Python 編程中,while 循環是一種非常重要的控制結構,用于重復執行一段代碼,直到滿足某個條件為止。本文將深入解析 while 循環的基本用法、高級技巧,并通過 15 個實踐案例幫助你更好地理解和應用這一強大的工具。
1. 基本語法
while 循環的基本語法如下:
while 條件:
# 執行的代碼塊
當條件為 True 時,循環體內的代碼會一直執行,直到條件變為 False。
示例 1:基本 while 循環
count = 0
while count < 5:
print(f"Count is {count}")
count += 1 # 每次循環后增加計數器
輸出結果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
2. 無限循環
如果 while 循環的條件始終為 True,則會導致無限循環。通常情況下,我們需要在循環體內設置一個條件來終止循環。
示例 2:無限循環
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break # 當用戶輸入 'q' 時,終止循環
3. 使用 break 和 continue
break 語句用于立即退出循環。
continue 語句用于跳過當前循環的剩余部分,直接進入下一次循環。
示例 3:使用 break
count = 0
while count < 10:
if count == 5:
break # 當計數器達到 5 時,退出循環
print(f"Count is {count}")
count += 1
輸出結果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
示例 4:使用 continue
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue # 跳過偶數
print(f"Odd number: {count}")
輸出結果:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
4. 嵌套 while 循環
可以在 while 循環內部再嵌套一個 while 循環,以實現更復雜的邏輯。
示例 5:嵌套 while 循環
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"({i}, {j})")
j += 1
i += 1
輸出結果:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
5. else 子句
while 循環可以包含一個 else 子句,當循環正常結束(即條件變為 False)時,else 子句中的代碼會被執行。
示例 6:else 子句
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
else:
print("Loop finished normally")
輸出結果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop finished normally
6. 處理異常
在 while 循環中,可以使用 try-except 語句來處理可能出現的異常。
示例 7:處理異常
while True:
try:
user_input = int(input("Enter a number: "))
print(f"You entered: {user_input}")
break
except ValueError:
print("Invalid input. Please enter a valid number.")
7. 使用 while 循環進行文件讀取
while 循環可以用于逐行讀取文件內容。
示例 8:逐行讀取文件
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip()) # 去除行末的換行符
line = file.readline()
假設 example.txt 文件內容如下:
Line 1
Line 2
Line 3
輸出結果:
Line 1
Line 2
Line 3
8. 使用 while 循環生成斐波那契數列
斐波那契數列是一個經典的數學問題,可以用 while 循環來生成。
示例 9:生成斐波那契數列
a, b = 0, 1
count = 0
while count < 10:
print(a)
a, b = b, a + b
count += 1
輸出結果:
0
1
1
2
3
5
8
13
21
34
9. 使用 while 循環實現簡單的猜數字游戲
示例 10:猜數字游戲
import random
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
user_guess = int(input("Guess the number (between 1 and 100): "))
attempts += 1
if user_guess == number_to_guess:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif user_guess < number_to_guess:
print("Too low, try again.")
else:
print("Too high, try again.")
10. 使用 while 循環實現倒計時
示例 11:倒計時
import time
seconds = 10
while seconds > 0:
print(f"Time remaining: {seconds} seconds")
time.sleep(1) # 暫停 1 秒
seconds -= 1
print("Time's up!")
11. 使用 while 循環實現簡單的計算器
示例 12:簡單計算器
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' to subtract two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "add":
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print(f"The result is {result}")
elif user_input == "subtract":
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 - num2
print(f"The result is {result}")
else:
print("Unknown command")
12. 使用 while 循環實現斐波那契數列的生成器
示例 13:斐波那契數列生成器
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(10):
print(next(fib))
輸出結果:
0
1
1
2
3
5
8
13
21
34
13. 使用 while 循環實現簡單的聊天機器人
示例 14:簡單聊天機器人
greetings = ["hello", "hi", "hey"]
responses = {
"hello": "Hi there!",
"hi": "Hello!",
"hey": "Hey!",
"how are you": "I'm just a computer program, but thanks for asking!",
"what's your name": "I'm a chatbot.",
"bye": "Goodbye!"
}
while True:
user_input = input("You: ").lower()
if user_input in greetings:
print(f"Bot: {responses[user_input]}")
elif user_input in responses:
print(f"Bot: {responses[user_input]}")
elif user_input == "exit":
break
else:
print("Bot: I don't understand that.")
14. 使用 while 循環實現簡單的密碼驗證
示例 15:密碼驗證
correct_password = "password123"
attempts = 0
while attempts < 3:
user_password = input("Enter your password: ")
if user_password == correct_password:
print("Access granted!")
break
else:
print("Incorrect password. Try again.")
attempts += 1
else:
print("Too many failed attempts. Access denied.")
實戰案例:實現一個簡單的銀行賬戶管理系統
假設我們要實現一個簡單的銀行賬戶管理系統,用戶可以存錢、取錢和查看余額。我們將使用 while 循環來處理用戶的操作。
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"Withdrew {amount}. New balance: {self.balance}")
def check_balance(self):
print(f"Current balance: {self.balance}")
# 創建一個銀行賬戶對象
account = BankAccount()
# 主循環
while True:
print("\nOptions:")
print("1. Deposit money")
print("2. Withdraw money")
print("3. Check balance")
print("4. Exit")
choice = input("Choose an option: ")
if choice == "1":
amount = float(input("Enter the amount to deposit: "))
account.deposit(amount)
elif choice == "2":
amount = float(input("Enter the amount to withdraw: "))
account.withdraw(amount)
elif choice == "3":
account.check_balance()
elif choice == "4":
print("Thank you for using our bank system. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
總結
本文詳細介紹了 Python 中 while 循環的基本用法、高級技巧,并通過 15 個實踐案例幫助你更好地理解和應用這一強大的工具。從基本的計數器到復雜的銀行賬戶管理系統,while 循環在各種場景中都有廣泛的應用。