文章目录
- 前言
- 一、while循环基础
-
- [1. 基本语法](#1. 基本语法)
- [2. 基础示例](#2. 基础示例)
- [3. 与for循环对比](#3. 与for循环对比)
- 二、无限循环与循环终止
-
- [1. 无限循环](#1. 无限循环)
- [2. 循环终止方法](#2. 循环终止方法)
- [3. 避免无限循环的技巧](#3. 避免无限循环的技巧)
- 三、循环与else子句
-
- [1. while-else基本用法](#1. while-else基本用法)
- [2. 实际应用场景](#2. 实际应用场景)
前言
本文主要介绍while循环基础、无限循环与循环终止和循环与else子句等知识点。
一、while循环基础
1. 基本语法
python
python
while 条件表达式:
# 循环体
# 当条件为True时执行
2. 基础示例
python
python
# 示例1:计数器
count = 0
while count < 5:
print(f"计数: {count}")
count += 1 # 重要:必须有改变条件的语句,否则会无限循环
print("循环结束")
# 输出:
# 计数: 0
# 计数: 1
# 计数: 2
# 计数: 3
# 计数: 4
# 循环结束
# 示例2:用户输入验证
password = ""
while password != "secret":
password = input("请输入密码:")
if password != "secret":
print("密码错误,请重试!")
print("密码正确,欢迎进入系统!")
# 示例3:计算数字之和
total = 0
num = 1
while num <= 100:
total += num
num += 1
print(f"1到100的和为: {total}") # 5050
3. 与for循环对比
python
python
# 用for循环实现同样的功能
# while循环:
count = 0
while count < 5:
print(count)
count += 1
# for循环(更简洁):
for i in range(5):
print(i)
# while更适合不确定循环次数的情况
# 示例:用户输入直到合法为止
valid_input = False
while not valid_input:
user_input = input("请输入1-10之间的数字:")
if user_input.isdigit():
num = int(user_input)
if 1 <= num <= 10:
valid_input = True
else:
print("数字不在1-10范围内!")
else:
print("请输入有效的数字!")
print(f"你输入了: {num}")
二、无限循环与循环终止
1. 无限循环
python
python
# 示例1:简单的无限循环
# while True:
# print("这是一个无限循环...")
# # 按Ctrl+C可以中断
# 示例2:服务器监听(模拟)
print("服务器启动,等待连接...")
connection_count = 0
while True:
# 模拟接收连接
user_input = input("输入'connect'模拟连接,'shutdown'关闭服务器: ")
if user_input == "connect":
connection_count += 1
print(f"第{connection_count}个客户端已连接")
elif user_input == "shutdown":
print("正在关闭服务器...")
break # 跳出无限循环
else:
print("未知命令")
print(f"服务器已关闭,总共处理了{connection_count}个连接")
# 示例3:游戏主循环(模拟)
game_running = True
player_health = 100
enemy_count = 3
print("游戏开始!")
while game_running:
print(f"\n玩家生命值: {player_health}")
print(f"敌人数量: {enemy_count}")
action = input("选择行动 (1:攻击, 2:治疗, 3:退出): ")
if action == "1": # 攻击
if enemy_count > 0:
enemy_count -= 1
player_health -= 10 # 受到反击伤害
print("攻击成功!消灭一个敌人")
else:
print("没有敌人了!")
elif action == "2": # 治疗
player_health = min(100, player_health + 30)
print("生命值恢复30点")
elif action == "3": # 退出
print("游戏结束")
game_running = False
else:
print("无效的选择")
# 检查游戏结束条件
if player_health <= 0:
print("玩家死亡,游戏结束!")
game_running = False
elif enemy_count == 0:
print("所有敌人都被消灭了,你赢了!")
game_running = False
2. 循环终止方法
break语句 - 立即终止循环
python
python
# 示例1:找到目标后立即停止
numbers = [23, 17, 45, 89, 32, 67, 54]
target = 89
index = 0
print("查找数字89:")
while index < len(numbers):
print(f"检查索引{index}: {numbers[index]}")
if numbers[index] == target:
print(f"找到了!索引为{index}")
break # 立即跳出循环
index += 1
# 示例2:密码尝试限制
max_attempts = 3
attempts = 0
correct_pin = "1234"
while attempts < max_attempts:
pin = input(f"第{attempts + 1}次尝试,请输入4位PIN码: ")
if len(pin) != 4 or not pin.isdigit():
print("PIN码必须是4位数字!")
continue # 跳过本次循环剩余部分
if pin == correct_pin:
print("PIN码正确,访问允许")
break
attempts += 1
print(f"PIN码错误,还剩{max_attempts - attempts}次尝试")
if attempts == max_attempts:
print("尝试次数过多,账户已锁定!")
# 示例3:多层循环中的break
row = 0
found = False
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("\n搜索数字5:")
while row < len(matrix):
col = 0
while col < len(matrix[row]):
print(f"检查 matrix[{row}][{col}] = {matrix[row][col]}")
if matrix[row][col] == 5:
print(f"找到数字5在位置 ({row}, {col})")
found = True
break # 跳出内层while循环
col += 1
if found:
break # 跳出外层while循环
row += 1
continue语句 - 跳过本次循环
python
# 示例:只处理正数
numbers = [10, -5, 23, -8, 45, 0, -12, 7]
index = 0
positive_sum = 0
print("处理正数:")
while index < len(numbers):
current = numbers[index]
index += 1
if current <= 0: # 跳过非正数
print(f"跳过 {current}")
continue
# 只处理正数
positive_sum += current
print(f"添加正数: {current}, 当前总和: {positive_sum}")
print(f"\n所有正数的总和: {positive_sum}")
# 示例2:跳过特定文件类型(模拟)
file_list = ["report.pdf", "data.xlsx", "photo.jpg", "notes.txt", "image.png", "config.ini"]
index = 0
text_files = []
image_extensions = [".jpg", ".png", ".gif", ".pdf"]
print("筛选文本文件:")
while index < len(file_list):
file = file_list[index]
index += 1
# 检查是否是图片文件
if any(file.endswith(ext) for ext in image_extensions):
print(f"跳过图片文件: {file}")
continue
# 只处理非图片文件
text_files.append(file)
print(f"添加文本文件: {file}")
print(f"\n找到的文本文件: {text_files}")
3. 避免无限循环的技巧
python
python
# 技巧1:设置最大迭代次数
max_iterations = 1000
iteration = 0
value = 1
# 计算2的幂,直到超过10000
while value < 10000:
if iteration >= max_iterations:
print("达到最大迭代次数,强制退出!")
break
print(f"2^{iteration} = {value}")
value *= 2
iteration += 1
# 技巧2:使用超时机制
import time
timeout = 5 # 5秒超时
start_time = time.time()
operation_count = 0
print("\n带超时的操作:")
while True:
# 模拟耗时操作
time.sleep(0.5) # 暂停0.5秒
operation_count += 1
# 检查是否超时
if time.time() - start_time > timeout:
print(f"操作超时!在{timeout}秒内完成了{operation_count}次操作")
break
print(f"完成第{operation_count}次操作...")
# 技巧3:设置安全计数器
counter = 0
max_attempts = 100
data = None
print("\n安全获取数据:")
while data is None and counter < max_attempts:
counter += 1
# 模拟有时成功有时失败的操作
import random
if random.random() > 0.7: # 30%的成功率
data = "获取到的数据"
print(f"第{counter}次尝试成功!")
else:
print(f"第{counter}次尝试失败...")
if counter >= max_attempts:
print("达到最大尝试次数,放弃!")
if data:
print(f"最终结果: {data}")
三、循环与else子句
Python的循环语句可以有一个else子句,它在循环正常完成(没有被break中断)时执行。
1. while-else基本用法
python
python
# 示例1:搜索目标,未找到时执行else
numbers = [23, 45, 67, 89, 12]
target = 100 # 不存在的目标
index = 0
print(f"搜索数字 {target}:")
while index < len(numbers):
print(f"检查 numbers[{index}] = {numbers[index]}")
if numbers[index] == target:
print(f"找到了!索引为 {index}")
break
index += 1
else:
# 只有在循环正常结束(没有break)时执行
print(f"未找到数字 {target}")
print("搜索完成")
# 输出:
# 搜索数字 100:
# 检查 numbers[0] = 23
# 检查 numbers[1] = 45
# 检查 numbers[2] = 67
# 检查 numbers[3] = 89
# 检查 numbers[4] = 12
# 未找到数字 100
# 搜索完成
# 示例2:验证密码,多次失败后锁定
max_attempts = 3
attempts = 0
correct_password = "python123"
print("密码验证系统")
while attempts < max_attempts:
password = input(f"第{attempts + 1}次尝试,请输入密码: ")
if password == correct_password:
print("密码正确,登录成功!")
break
attempts += 1
print(f"密码错误,还剩{max_attempts - attempts}次尝试")
else:
# 循环正常结束(所有尝试都失败)
print("尝试次数过多,账户已锁定30分钟!")
# 示例3:检查列表是否已排序
def is_sorted(numbers):
"""检查列表是否已排序(升序)"""
i = 0
while i < len(numbers) - 1:
if numbers[i] > numbers[i + 1]:
return False # 发现逆序对
i += 1
else:
# 循环正常完成,说明列表已排序
return True
# 测试
test_cases = [
[1, 2, 3, 4, 5], # 已排序
[5, 3, 1, 4, 2], # 未排序
[10, 20, 30], # 已排序
[1] # 单元素列表
]
for test in test_cases:
result = is_sorted(test)
print(f"列表 {test} 是否已排序: {result}")
2. 实际应用场景
python
python
# 场景1:等待资源就绪
import random
import time
def wait_for_resource(timeout=10, check_interval=0.5):
"""等待资源就绪,带超时机制"""
start_time = time.time()
attempts = 0
print("等待资源就绪...")
while time.time() - start_time < timeout:
attempts += 1
# 模拟检查资源(随机成功)
if random.random() > 0.8: # 20%的成功率
print(f"第{attempts}次检查:资源已就绪!")
return True
print(f"第{attempts}次检查:资源未就绪,等待{check_interval}秒...")
time.sleep(check_interval)
else:
# 超时后执行
print(f"等待超时({timeout}秒),资源仍未就绪")
return False
# 使用
if wait_for_resource(timeout=5):
print("可以开始处理资源")
else:
print("资源未就绪,执行备用方案")
# 场景2:网络请求重试机制
def make_request_with_retry(max_retries=3):
"""带重试机制的网络请求"""
retry_count = 0
while retry_count < max_retries:
try:
# 模拟网络请求(可能失败)
print(f"第{retry_count + 1}次尝试发送请求...")
# 随机模拟成功或失败
if random.random() > 0.4: # 60%成功率
print("请求成功!")
return {"status": "success", "data": "响应数据"}
else:
raise ConnectionError("网络连接失败")
except Exception as e:
retry_count += 1
print(f"请求失败: {e}")
if retry_count < max_retries:
print(f"{max_retries - retry_count}次重试机会,等待2秒后重试...")
time.sleep(2)
else:
# 所有重试都失败
print(f"所有{max_retries}次尝试都失败了")
return {"status": "error", "message": "请求失败"}
# 使用
result = make_request_with_retry(max_retries=3)
print(f"最终结果: {result}")
# 场景3:数据验证与清理
def process_data_stream():
"""处理数据流,遇到无效数据跳过"""
data_stream = [
{"id": 1, "value": 100},
{"id": 2, "value": None}, # 无效数据
{"id": 3, "value": 200},
{"id": 4, "value": "abc"}, # 无效数据
{"id": 5, "value": 300},
{"id": 6, "value": 0} # 边界值
]
index = 0
valid_count = 0
total_value = 0
print("处理数据流:")
while index < len(data_stream):
item = data_stream[index]
index += 1
# 数据验证
value = item.get("value")
if value is None or not isinstance(value, (int, float)):
print(f"跳过无效数据: ID={item['id']}, value={value}")
continue
# 处理有效数据
valid_count += 1
total_value += value
print(f"处理有效数据: ID={item['id']}, value={value}")
else:
# 循环正常结束
if valid_count > 0:
average = total_value / valid_count
print(f"\n处理完成!")
print(f"有效数据: {valid_count}条")
print(f"总值: {total_value}")
print(f"平均值: {average:.2f}")
else:
print("\n没有有效数据可供处理")
# 执行
process_data_stream()