AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Python while循環的 12 個魔法技巧與實戰案例

來源: 責編: 時間:2024-06-19 15:36:42 163觀看
導讀今天我們要一起探索的是Python編程中一個超級實用又有趣的部分——while循環!想象一下,就像哈利波特的魔杖,while循環能讓我們一遍遍施展魔法,直到條件不再滿足。我們開始這場魔法之旅吧!1. 基礎施法:Hello, World! 循環版m

今天我們要一起探索的是Python編程中一個超級實用又有趣的部分——while循環!想象一下,就像哈利波特的魔杖,while循環能讓我們一遍遍施展魔法,直到條件不再滿足。我們開始這場魔法之旅吧!13928資訊網——每日最新資訊28at.com

13928資訊網——每日最新資訊28at.com

1. 基礎施法:Hello, World! 循環版

message = "Hello, World!"count = 0while count < 5:    print(message)    count += 1

這段代碼就是我們的魔法咒語,它會重復打印“Hello, World!”五次。while count < 5:是我們的魔法條件,只要計數器count小于5,咒語就繼續生效!13928資訊網——每日最新資訊28at.com

2. 魔法數字猜猜猜

讓我們來玩個游戲吧!計算機想了一個1到10之間的數字,你來猜。13928資訊網——每日最新資訊28at.com

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}!")

通過循環,直到你猜對為止,是不是很神奇?13928資訊網——每日最新資訊28at.com

3. 施展無限循環的禁忌

小心使用!下面的代碼會陷入無盡的循環,除非手動停止程序。13928資訊網——每日最新資訊28at.com

# 千萬不要輕易嘗試!while True:    print("這可能會永遠持續下去...")

這個“無限循環”在實際編程中要慎用,但有時也能成為解決問題的巧妙手段。13928資訊網——每日最新資訊28at.com

4. 使用break,逃離循環的束縛

當我們達到某個特定條件時,可以使用break咒語逃離循環。13928資訊網——每日最新資訊28at.com

count = 0while True:    if count == 5:        break    print(count)    count += 1

一旦count達到5,我們就成功逃出了循環的圈套!13928資訊網——每日最新資訊28at.com

5. continue:跳過不想執行的部分

想象你在數數,但跳過偶數。13928資訊網——每日最新資訊28at.com

num = 0while num < 10:    num += 1    if num % 2 == 0:  # 如果是偶數        continue  # 跳過這次循環,直接檢查下一個數    print(num)

這樣,就只打印奇數了,巧妙地避開了偶數。13928資訊網——每日最新資訊28at.com

6. 列表中的循環旅行

讓我們遍歷一個列表,每次取出一個元素。13928資訊網——每日最新資訊28at.com

fruits = ["蘋果", "香蕉", "櫻桃"]index = 0while index < len(fruits):    print(fruits[index])    index += 1

就像在水果園里漫步,依次欣賞每個美味的果實。13928資訊網——每日最新資訊28at.com

7. 嵌套循環:雙重魔法

嵌套循環就像施展多重咒語,一層接一層。13928資訊網——每日最新資訊28at.com

rows = 5while rows > 0:    cols = 5    while cols > 0:        print("*", end=" ")        cols -= 1    print()  # 換行    rows -= 1

這段代碼會打印出一個星號的小金字塔,是不是很酷?13928資訊網——每日最新資訊28at.com

8. 循環控制之else子句

你知道嗎?while循環后面還可以跟一個else,它會在循環正常結束(即沒有被break中斷)時執行。13928資訊網——每日最新資訊28at.com

number = 10found = Falsewhile number > 0:    if number == 5:        found = True        break    number -= 1else:    print("沒找到數字5。")

如果找到了數字5,循環就會被break,else部分不會執行。如果沒有找到,else的內容才會展現。13928資訊網——每日最新資訊28at.com

9. 計算機的耐心:計算階乘

讓我們用while循環來計算一個數的階乘。13928資訊網——每日最新資訊28at.com

number = 5factorial = 1while number > 1:    factorial *= number    number -= 1print(f"{5}的階乘是{factorial}")

這是數學和編程的美妙結合,簡單而強大。13928資訊網——每日最新資訊28at.com

10. 模擬倒計時火箭發射

countdown = 10print("準備發射...")while countdown > 0:    print(countdown)    countdown -= 1print("點火!升空!")

模擬緊張刺激的倒計時,感受即將飛向太空的激動!13928資訊網——每日最新資訊28at.com

11. 文件讀取:逐行施法

利用while循環逐行讀取文件內容,就像一頁頁翻閱魔法書。13928資訊網——每日最新資訊28at.com

with open("magic_book.txt", "r") as file:    line = file.readline()    while line:        print(line.strip())  # 去掉換行符        line = file.readline()

記得替換"magic_book.txt"為你的文件名哦!13928資訊網——每日最新資訊28at.com

12. 自動化測試的循環助手

在自動化測試場景中,我們可能需要不斷嘗試直到某個條件達成。13928資訊網——每日最新資訊28at.com

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("嘗試次數過多,登錄失敗。")

這展示了如何在不確定成功次數的情況下耐心嘗試。13928資訊網——每日最新資訊28at.com

進階技巧

13. 利用enumerate和while優化遍歷

通常,我們用for循環配合enumerate遍歷列表時很常見,但while同樣能完成這項任務,只是方式不同。13928資訊網——每日最新資訊28at.com

fruits = ['apple', 'banana', 'cherry']index = 0while index < len(fruits):    fruit, index = fruits[index], index + 1    print(fruit)

這里,我們通過同時更新索引和訪問元素,模擬了enumerate的效果,展現了while循環的靈活性。13928資訊網——每日最新資訊28at.com

14. 無限循環的高效利用:生成器

雖然之前提到了無限循環的禁忌,但當結合生成器時,它可以變得非常有用。13928資訊網——每日最新資訊28at.com

def count_up():    num = 1    while True:        yield num        num += 1counter = count_up()for _ in range(5):    print(next(counter))

這段代碼創建了一個無限遞增的數字生成器。通過yield,我們可以在需要時暫停并恢復循環,非常節省資源。13928資訊網——每日最新資訊28at.com

15. 循環優化:避免死循環

在設計循環時,確保總有跳出循環的途徑。使用break或合適的條件判斷,防止程序陷入死循環。良好的循環設計是代碼健壯性的體現。13928資訊網——每日最新資訊28at.com

16. 實戰:斐波那契數列

斐波那契數列是一個經典的編程練習,讓我們用while循環來實現它。13928資訊網——每日最新資訊28at.com

a, b = 0, 1count = 0while count < 10:    print(a, end=" ")    nth = a + b    a = b    b = nth    count += 1

這段代碼展示了如何使用while循環生成斐波那契數列的前10項,通過不斷地交換變量值來達到目的。13928資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-94848-0.htmlPython while循環的 12 個魔法技巧與實戰案例

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 為什么高手都要用非阻塞IO?

下一篇: Go必知必會:并發編程的核心channel

標簽:
  • 熱門焦點
Top