Python while循環(huán)的 12 個魔法技巧與實戰(zhàn)案例
今天我們要一起探索的是Python編程中一個超級實用又有趣的部分——while循環(huán)!想象一下,就像哈利波特的魔杖,while循環(huán)能讓我們一遍遍施展魔法,直到條件不再滿足。我們開始這場魔法之旅吧!
1. 基礎施法:Hello, World! 循環(huán)版
message = "Hello, World!"
count = 0
while count < 5:
print(message)
count += 1
這段代碼就是我們的魔法咒語,它會重復打印“Hello, World!”五次。while count < 5:是我們的魔法條件,只要計數器count小于5,咒語就繼續(xù)生效!
2. 魔法數字猜猜猜
讓我們來玩?zhèn)€游戲吧!計算機想了一個1到10之間的數字,你來猜。
import random
number_to_guess = random.randint(1, 10)
guess = None
print("我想了一個1到10的數字,你能猜到嗎?")
while guess != number_to_guess:
guess = int(input("你的猜測是:"))
if guess < number_to_guess:
print("太低了,再試試。")
elif guess > number_to_guess:
print("太高了,加油!")
print(f"恭喜你,猜對了!數字就是{number_to_guess}!")
通過循環(huán),直到你猜對為止,是不是很神奇?
3. 施展無限循環(huán)的禁忌
小心使用!下面的代碼會陷入無盡的循環(huán),除非手動停止程序。
# 千萬不要輕易嘗試!
while True:
print("這可能會永遠持續(xù)下去...")
這個“無限循環(huán)”在實際編程中要慎用,但有時也能成為解決問題的巧妙手段。
4. 使用break,逃離循環(huán)的束縛
當我們達到某個特定條件時,可以使用break咒語逃離循環(huán)。
count = 0
while True:
if count == 5:
break
print(count)
count += 1
一旦count達到5,我們就成功逃出了循環(huán)的圈套!
5. continue:跳過不想執(zhí)行的部分
想象你在數數,但跳過偶數。
num = 0
while num < 10:
num += 1
if num % 2 == 0: # 如果是偶數
continue # 跳過這次循環(huán),直接檢查下一個數
print(num)
這樣,就只打印奇數了,巧妙地避開了偶數。
6. 列表中的循環(huán)旅行
讓我們遍歷一個列表,每次取出一個元素。
fruits = ["蘋果", "香蕉", "櫻桃"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
就像在水果園里漫步,依次欣賞每個美味的果實。
7. 嵌套循環(huán):雙重魔法
嵌套循環(huán)就像施展多重咒語,一層接一層。
rows = 5
while rows > 0:
cols = 5
while cols > 0:
print("*", end=" ")
cols -= 1
print() # 換行
rows -= 1
這段代碼會打印出一個星號的小金字塔,是不是很酷?
8. 循環(huán)控制之else子句
你知道嗎?while循環(huán)后面還可以跟一個else,它會在循環(huán)正常結束(即沒有被break中斷)時執(zhí)行。
number = 10
found = False
while number > 0:
if number == 5:
found = True
break
number -= 1
else:
print("沒找到數字5。")
如果找到了數字5,循環(huán)就會被break,else部分不會執(zhí)行。如果沒有找到,else的內容才會展現。
9. 計算機的耐心:計算階乘
讓我們用while循環(huán)來計算一個數的階乘。
number = 5
factorial = 1
while number > 1:
factorial *= number
number -= 1
print(f"{5}的階乘是{factorial}")
這是數學和編程的美妙結合,簡單而強大。
10. 模擬倒計時火箭發(fā)射
countdown = 10
print("準備發(fā)射...")
while countdown > 0:
print(countdown)
countdown -= 1
print("點火!升空!")
模擬緊張刺激的倒計時,感受即將飛向太空的激動!
11. 文件讀取:逐行施法
利用while循環(huán)逐行讀取文件內容,就像一頁頁翻閱魔法書。
with open("magic_book.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # 去掉換行符
line = file.readline()
記得替換"magic_book.txt"為你的文件名哦!
12. 自動化測試的循環(huán)助手
在自動化測試場景中,我們可能需要不斷嘗試直到某個條件達成。
success = False
attempt = 0
max_attempts = 5
while not success and attempt < max_attempts:
# 這里進行測試操作,比如網頁登錄
print(f"嘗試第{attempt+1}次登錄...")
# 假設success是在某個條件滿足后設置為True
if some_test_condition(): # 假設函數判斷是否成功
success = True
else:
attempt += 1
if success:
print("登錄成功!")
else:
print("嘗試次數過多,登錄失敗。")
這展示了如何在不確定成功次數的情況下耐心嘗試。
進階技巧
13. 利用enumerate和while優(yōu)化遍歷
通常,我們用for循環(huán)配合enumerate遍歷列表時很常見,但while同樣能完成這項任務,只是方式不同。
fruits = ['apple', 'banana', 'cherry']
index = 0
while index < len(fruits):
fruit, index = fruits[index], index + 1
print(fruit)
這里,我們通過同時更新索引和訪問元素,模擬了enumerate的效果,展現了while循環(huán)的靈活性。
14. 無限循環(huán)的高效利用:生成器
雖然之前提到了無限循環(huán)的禁忌,但當結合生成器時,它可以變得非常有用。
def count_up():
num = 1
while True:
yield num
num += 1
counter = count_up()
for _ in range(5):
print(next(counter))
這段代碼創(chuàng)建了一個無限遞增的數字生成器。通過yield,我們可以在需要時暫停并恢復循環(huán),非常節(jié)省資源。
15. 循環(huán)優(yōu)化:避免死循環(huán)
在設計循環(huán)時,確??傆刑鲅h(huán)的途徑。使用break或合適的條件判斷,防止程序陷入死循環(huán)。良好的循環(huán)設計是代碼健壯性的體現。
16. 實戰(zhàn):斐波那契數列
斐波那契數列是一個經典的編程練習,讓我們用while循環(huán)來實現它。
a, b = 0, 1
count = 0
while count < 10:
print(a, end=" ")
nth = a + b
a = b
b = nth
count += 1
這段代碼展示了如何使用while循環(huán)生成斐波那契數列的前10項,通過不斷地交換變量值來達到目的。