循环控制 #
循环控制语句用于改变循环的执行流程。
一、break语句 #
1.1 基本用法 #
break 用于立即跳出当前循环。
python
# 跳出for循环
for i in range(10):
if i == 5:
break
print(i)
# 输出:0 1 2 3 4
# 跳出while循环
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# 输出:0 1 2 3 4
1.2 查找元素 #
python
# 查找第一个满足条件的元素
numbers = [1, 3, 5, 7, 8, 9, 10]
for n in numbers:
if n % 2 == 0:
print(f"找到第一个偶数:{n}")
break
# 输出:找到第一个偶数:8
1.3 用户输入验证 #
python
# 限制尝试次数
max_attempts = 3
for attempt in range(max_attempts):
password = input("请输入密码:")
if password == "secret":
print("登录成功!")
break
else:
remaining = max_attempts - attempt - 1
print(f"密码错误,还剩{remaining}次机会")
else:
print("尝试次数过多,账户已锁定")
1.4 嵌套循环中的break #
python
# break只跳出最内层循环
for i in range(3):
for j in range(3):
if j == 1:
break # 只跳出内层循环
print(f"({i}, {j})")
# 输出:
# (0, 0)
# (1, 0)
# (2, 0)
# 跳出多层循环(使用标志位)
found = False
for i in range(5):
for j in range(5):
if i * j > 10:
found = True
break
if found:
break
print(f"找到:i={i}, j={j}")
# 使用函数返回
def find_target():
for i in range(5):
for j in range(5):
if i * j > 10:
return i, j
return None, None
i, j = find_target()
1.5 break与else #
python
# break会跳过else块
for i in range(5):
if i == 3:
break
print(i)
else:
print("循环正常结束") # 不会执行
# 正常结束时执行else
for i in range(3):
print(i)
else:
print("循环正常结束") # 会执行
# 输出:0 1 2 循环正常结束
二、continue语句 #
2.1 基本用法 #
continue 用于跳过当前迭代,继续下一次迭代。
python
# 跳过特定值
for i in range(5):
if i == 2:
continue
print(i)
# 输出:0 1 3 4
# 跳过奇数
for i in range(10):
if i % 2 != 0:
continue
print(i)
# 输出:0 2 4 6 8
2.2 过滤数据 #
python
# 只处理有效数据
data = [1, None, 2, None, 3, 4, None, 5]
for item in data:
if item is None:
continue
print(f"处理:{item}")
# 输出:处理:1, 处理:2, 处理:3, 处理:4, 处理:5
# 过滤无效输入
inputs = ["hello", "", "world", " ", "python"]
for text in inputs:
stripped = text.strip()
if not stripped: # 空字符串
continue
print(f"处理:'{stripped}'")
# 输出:处理:'hello', 处理:'world', 处理:'python'
2.3 数据验证 #
python
# 验证用户数据
users = [
{"name": "Tom", "age": 25, "email": "tom@example.com"},
{"name": "", "age": 30, "email": "user2@example.com"},
{"name": "Jerry", "age": -5, "email": "jerry@example.com"},
{"name": "Alice", "age": 28, "email": ""},
{"name": "Bob", "age": 35, "email": "bob@example.com"}
]
for user in users:
# 验证名字
if not user["name"]:
print(f"跳过:名字为空")
continue
# 验证年龄
if user["age"] <= 0:
print(f"跳过:{user['name']} 年龄无效")
continue
# 验证邮箱
if not user["email"]:
print(f"跳过:{user['name']} 邮箱为空")
continue
print(f"有效用户:{user['name']}")
# 输出:
# 有效用户:Tom
# 跳过:名字为空
# 跳过:Jerry 年龄无效
# 跳过:Alice 邮箱为空
# 有效用户:Bob
2.4 continue与代码可读性 #
python
# 使用continue减少嵌套
# 不推荐:深层嵌套
def process_items(items):
for item in items:
if item.is_valid:
if item.has_data:
if item.is_ready:
process(item)
# 推荐:提前continue
def process_items(items):
for item in items:
if not item.is_valid:
continue
if not item.has_data:
continue
if not item.is_ready:
continue
process(item)
2.5 continue与else #
python
# continue不会影响else
for i in range(5):
if i == 2:
continue
print(i)
else:
print("循环正常结束")
# 输出:0 1 3 4 循环正常结束
三、循环的else子句 #
3.1 基本语法 #
python
# else在循环正常结束时执行
for i in range(3):
print(i)
else:
print("循环结束")
# 输出:0 1 2 循环结束
# while循环的else
count = 0
while count < 3:
print(count)
count += 1
else:
print("循环结束")
# 输出:0 1 2 循环结束
3.2 查找模式 #
python
# 查找元素,找不到时执行else
def find_user(users, name):
for user in users:
if user["name"] == name:
return user
return None
# 使用for-else实现
def find_user_v2(users, name):
for user in users:
if user["name"] == name:
print(f"找到用户:{user}")
break
else:
print(f"未找到用户:{name}")
users = [{"name": "Tom"}, {"name": "Jerry"}]
find_user_v2(users, "Tom") # 找到用户:{'name': 'Tom'}
find_user_v2(users, "Alice") # 未找到用户:Alice
3.3 验证模式 #
python
# 验证所有元素都满足条件
numbers = [2, 4, 6, 8, 10]
for n in numbers:
if n % 2 != 0:
print("发现奇数")
break
else:
print("全是偶数")
# 输出:全是偶数
# 使用all更简洁
if all(n % 2 == 0 for n in numbers):
print("全是偶数")
3.4 检查素数 #
python
def is_prime(n):
"""检查n是否为素数"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False # 找到因子,不是素数
else:
return True # 没找到因子,是素数
print(is_prime(7)) # True
print(is_prime(10)) # False
3.5 重试模式 #
python
import random
def try_operation(max_retries=3):
"""尝试操作,成功返回True"""
for attempt in range(max_retries):
print(f"第{attempt + 1}次尝试...")
# 模拟操作
if random.random() > 0.7: # 30%成功率
print("操作成功!")
break
else:
print("所有尝试都失败了")
return False
return True
try_operation()
四、综合应用 #
4.1 菜单系统 #
python
def menu_system():
"""简单的菜单系统"""
while True:
print("\n=== 菜单 ===")
print("1. 新建")
print("2. 打开")
print("3. 保存")
print("0. 退出")
choice = input("请选择:")
if choice == '0':
print("再见!")
break
elif choice == '1':
print("新建文件...")
elif choice == '2':
print("打开文件...")
elif choice == '3':
print("保存文件...")
else:
print("无效选择,请重试")
continue
print("操作完成")
# menu_system()
4.2 数据处理管道 #
python
def process_data(data):
"""数据处理管道"""
results = []
for item in data:
# 跳过空值
if item is None:
continue
# 跳过无效值
try:
value = float(item)
except (ValueError, TypeError):
continue
# 跳过负数
if value < 0:
continue
# 处理有效数据
results.append(value ** 2)
return results
data = [1, None, "2", "invalid", -3, 4, "5.5"]
print(process_data(data)) # [1.0, 4.0, 16.0, 30.25]
4.3 游戏循环 #
python
def game_loop():
"""简单的游戏循环"""
score = 0
lives = 3
while lives > 0:
# 游戏逻辑
print(f"\n分数:{score},生命:{lives}")
action = input("输入'action'得分,'quit'退出:")
if action == 'quit':
print("游戏结束!")
break
elif action == 'action':
score += 10
print(f"得分!当前分数:{score}")
else:
lives -= 1
print(f"操作错误,失去一条生命")
else:
print("游戏结束,生命耗尽!")
print(f"最终分数:{score}")
# game_loop()
五、常见陷阱 #
5.1 在finally中使用break/continue #
python
# 不能在finally块中使用break/continue
# for i in range(5):
# try:
# pass
# finally:
# break # SyntaxError
5.2 循环变量作用域 #
python
# 循环变量在循环外仍可访问
for i in range(5):
pass
print(i) # 4(循环变量的最后值)
# while循环
while False:
x = 1
# print(x) # NameError(如果循环一次都没执行)
5.3 continue与资源清理 #
python
# 使用continue时注意资源清理
def process_files(filenames):
for filename in filenames:
f = open(filename, 'r')
if should_skip(filename):
continue # 文件没有关闭!
process(f)
f.close()
# 正确方式
def process_files_v2(filenames):
for filename in filenames:
with open(filename, 'r') as f:
if should_skip(filename):
continue # with会自动关闭文件
process(f)
六、最佳实践 #
6.1 使用break代替标志变量 #
python
# 不推荐
found = False
for item in items:
if condition(item):
found = True
break
if found:
handle_found()
# 推荐
for item in items:
if condition(item):
handle_found()
break
else:
handle_not_found()
6.2 使用continue减少嵌套 #
python
# 不推荐:深层嵌套
for item in items:
if condition1(item):
if condition2(item):
if condition3(item):
process(item)
# 推荐:使用continue
for item in items:
if not condition1(item):
continue
if not condition2(item):
continue
if not condition3(item):
continue
process(item)
6.3 合理使用else #
python
# else适合"没找到"的情况
for item in items:
if is_target(item):
handle_found(item)
break
else:
handle_not_found()
# 不适合复杂的后处理
for item in items:
process(item)
else:
# 这里容易被忽略
cleanup()
七、总结 #
| 语句 | 用途 |
|---|---|
break |
立即跳出循环 |
continue |
跳过当前迭代 |
else |
循环正常结束后执行 |
关键点:
break会跳过else块continue不会影响else块- 嵌套循环中
break只跳出最内层 - 使用
for-else实现查找模式
最后更新:2026-03-16