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