Python 中的 while 循環(huán)控制結(jié)構(gòu)深度解析與 15 個(gè)實(shí)踐案例
在 Python 編程中,while 循環(huán)是一種非常重要的控制結(jié)構(gòu),用于重復(fù)執(zhí)行一段代碼,直到滿足某個(gè)條件為止。本文將深入解析 while 循環(huán)的基本用法、高級(jí)技巧,并通過(guò) 15 個(gè)實(shí)踐案例幫助你更好地理解和應(yīng)用這一強(qiáng)大的工具。
1. 基本語(yǔ)法
while 循環(huán)的基本語(yǔ)法如下:
while 條件:
# 執(zhí)行的代碼塊
當(dāng)條件為 True 時(shí),循環(huán)體內(nèi)的代碼會(huì)一直執(zhí)行,直到條件變?yōu)?nbsp;False。
示例 1:基本 while 循環(huán)
count = 0
while count < 5:
print(f"Count is {count}")
count += 1 # 每次循環(huán)后增加計(jì)數(shù)器
輸出結(jié)果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
2. 無(wú)限循環(huán)
如果 while 循環(huán)的條件始終為 True,則會(huì)導(dǎo)致無(wú)限循環(huán)。通常情況下,我們需要在循環(huán)體內(nèi)設(shè)置一個(gè)條件來(lái)終止循環(huán)。
示例 2:無(wú)限循環(huán)
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break # 當(dāng)用戶(hù)輸入 'q' 時(shí),終止循環(huán)
3. 使用 break 和 continue
break 語(yǔ)句用于立即退出循環(huán)。
continue 語(yǔ)句用于跳過(guò)當(dāng)前循環(huán)的剩余部分,直接進(jìn)入下一次循環(huán)。
示例 3:使用 break
count = 0
while count < 10:
if count == 5:
break # 當(dāng)計(jì)數(shù)器達(dá)到 5 時(shí),退出循環(huán)
print(f"Count is {count}")
count += 1
輸出結(jié)果:
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 # 跳過(guò)偶數(shù)
print(f"Odd number: {count}")
輸出結(jié)果:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
4. 嵌套 while 循環(huán)
可以在 while 循環(huán)內(nèi)部再嵌套一個(gè) while 循環(huán),以實(shí)現(xiàn)更復(fù)雜的邏輯。
示例 5:嵌套 while 循環(huán)
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"({i}, {j})")
j += 1
i += 1
輸出結(jié)果:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
5. else 子句
while 循環(huán)可以包含一個(gè) else 子句,當(dāng)循環(huán)正常結(jié)束(即條件變?yōu)?nbsp;False)時(shí),else 子句中的代碼會(huì)被執(zhí)行。
示例 6:else 子句
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
else:
print("Loop finished normally")
輸出結(jié)果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop finished normally
6. 處理異常
在 while 循環(huán)中,可以使用 try-except 語(yǔ)句來(lái)處理可能出現(xiàn)的異常。
示例 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 循環(huán)進(jìn)行文件讀取
while 循環(huán)可以用于逐行讀取文件內(nèi)容。
示例 8:逐行讀取文件
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip()) # 去除行末的換行符
line = file.readline()
假設(shè) example.txt 文件內(nèi)容如下:
Line 1
Line 2
Line 3
輸出結(jié)果:
Line 1
Line 2
Line 3
8. 使用 while 循環(huán)生成斐波那契數(shù)列
斐波那契數(shù)列是一個(gè)經(jīng)典的數(shù)學(xué)問(wèn)題,可以用 while 循環(huán)來(lái)生成。
示例 9:生成斐波那契數(shù)列
a, b = 0, 1
count = 0
while count < 10:
print(a)
a, b = b, a + b
count += 1
輸出結(jié)果:
0
1
1
2
3
5
8
13
21
34
9. 使用 while 循環(huán)實(shí)現(xiàn)簡(jiǎn)單的猜數(shù)字游戲
示例 10:猜數(shù)字游戲
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 循環(huán)實(shí)現(xiàn)倒計(jì)時(shí)
示例 11:倒計(jì)時(shí)
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 循環(huán)實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器
示例 12:簡(jiǎn)單計(jì)算器
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 循環(huán)實(shí)現(xiàn)斐波那契數(shù)列的生成器
示例 13:斐波那契數(shù)列生成器
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(10):
print(next(fib))
輸出結(jié)果:
0
1
1
2
3
5
8
13
21
34
13. 使用 while 循環(huán)實(shí)現(xiàn)簡(jiǎn)單的聊天機(jī)器人
示例 14:簡(jiǎn)單聊天機(jī)器人
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 循環(huán)實(shí)現(xiàn)簡(jiǎn)單的密碼驗(yàn)證
示例 15:密碼驗(yàn)證
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.")
實(shí)戰(zhàn)案例:實(shí)現(xiàn)一個(gè)簡(jiǎn)單的銀行賬戶(hù)管理系統(tǒng)
假設(shè)我們要實(shí)現(xiàn)一個(gè)簡(jiǎn)單的銀行賬戶(hù)管理系統(tǒng),用戶(hù)可以存錢(qián)、取錢(qián)和查看余額。我們將使用 while 循環(huán)來(lái)處理用戶(hù)的操作。
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}")
# 創(chuàng)建一個(gè)銀行賬戶(hù)對(duì)象
account = BankAccount()
# 主循環(huán)
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.")
總結(jié)
本文詳細(xì)介紹了 Python 中 while 循環(huán)的基本用法、高級(jí)技巧,并通過(guò) 15 個(gè)實(shí)踐案例幫助你更好地理解和應(yīng)用這一強(qiáng)大的工具。從基本的計(jì)數(shù)器到復(fù)雜的銀行賬戶(hù)管理系統(tǒng),while 循環(huán)在各種場(chǎng)景中都有廣泛的應(yīng)用。