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 循环在各种场景中都有广泛的应用。

好了,今天的分享就到这里了,我们下期见。

相关推荐

天龙唐门心法怎么获得
best365官网登录下载

天龙唐门心法怎么获得

⌛ 07-09 👁️ 3580
【人人讲安全】浅谈安全习惯的养成
365赢多少钱会被限额

【人人讲安全】浅谈安全习惯的养成

⌛ 07-11 👁️ 3501
微店怎么搜索不到店铺? , 微店为什么不能搜索店铺
best365官网登录下载

微店怎么搜索不到店铺? , 微店为什么不能搜索店铺

⌛ 07-07 👁️ 3619