成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Python 中的 while 循環控制結構深度解析與 15 個實踐案例

開發
本文詳細介紹了 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 循環在各種場景中都有廣泛的應用。

責任編輯:趙寧寧 來源: 手把手PythonAI編程
相關推薦

2024-06-19 10:08:42

Python編程while循環

2024-08-06 16:04:03

2010-09-08 17:00:22

SQLWHILE循環

2024-11-08 16:13:43

Python開發

2024-11-27 10:44:48

2024-08-30 09:53:17

Java 8編程集成

2025-03-27 04:10:00

2023-04-20 13:59:01

Pythonwhile循環的

2024-05-20 10:00:00

代碼Python編程

2024-09-19 08:49:13

2024-02-26 12:13:32

C++開發編程

2020-06-30 08:27:56

Python開發工具

2024-05-29 12:39:55

2022-01-17 21:08:54

Python 循環結構

2023-12-04 16:18:30

2025-05-12 01:33:00

異步函數Promise

2010-10-28 09:05:42

SilverlightXAML

2025-02-28 07:09:25

2021-12-09 23:20:31

Python循環語句

2010-10-08 09:52:18

JavaScript匿
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 午夜男人天堂 | 日韩精品久久 | 91深夜福利视频 | 在线视频国产一区 | 国产色播av在线 | 国产一区二区三区四区三区四 | 亚洲精品一区二区三区中文字幕 | 天天干夜夜拍 | 午夜精品一区二区三区在线 | 精品国产欧美一区二区三区成人 | 中文字幕一区二区三区精彩视频 | 狠狠狠色丁香婷婷综合久久五月 | 二区在线视频 | 国产精品国产精品国产专区不蜜 | 日韩av美女电影 | 中文字幕中文字幕 | 欧美日韩免费视频 | 亚洲欧美日韩在线不卡 | 国产欧美视频一区 | 久久躁日日躁aaaaxxxx | 成人毛片视频免费 | 成年人网站免费 | 日韩精品成人免费观看视频 | 国产午夜精品一区二区三区四区 | 91精品国产乱码久久久 | 大久| 91麻豆精品国产91久久久资源速度 | 成人国产一区二区三区精品麻豆 | 国产精品视频播放 | 播放一级黄色片 | 韩日一区二区三区 | 中文字幕日韩一区 | 午夜tv免费观看 | 男女精品网站 | 一级黄色录像毛片 | 国产日韩精品在线 | 欧美在线观看一区 | 韩国主播午夜大尺度福利 | 精品视频在线播放 | 黑色丝袜三级在线播放 | 手机av在线 |