# Python流程控制详解:从条件判断到循环结构的核心语法
## 引言:编程的逻辑基石
流程控制是编程语言的神经系统,它决定了代码的执行路径和逻辑流程。Python以其清晰简洁的语法,提供了强大而灵活的流程控制机制。掌握条件判断和循环结构不仅是学习Python的基础,更是培养编程思维的关键。本文将从基础到实践,深入解析Python的流程控制语法。
## 条件判断:if-elif-else结构
Python的条件判断语法直观易懂,但其中蕴含的逻辑表达技巧值得深入探讨。
### 基础条件判断
```python
# 条件判断基础示例
def basic_condition_demo():
"""基础条件判断演示"""
# 1. 简单的if语句
age = 20
if age >= 18:
print("已成年,可以进入")
# 2. if-else结构
temperature = 25
if temperature > 30:
print("天气炎热")
else:
print("天气宜人")
# 3. if-elif-else多重条件
score = 85
if score >= 90:
grade = "A"
evaluation = "优秀"
elif score >= 80:
grade = "B"
evaluation = "良好"
elif score >= 70:
grade = "C"
evaluation = "中等"
elif score >= 60:
grade = "D"
evaluation = "及格"
else:
grade = "F"
evaluation = "不及格"
print(f"分数: {score}, 等级: {grade}, 评价: {evaluation}")
# 4. 嵌套条件判断
is_member = True
purchase_amount = 1200
if is_member:
if purchase_amount > 1000:
discount = 0.2
print("会员大额消费,享受8折优惠")
else:
discount = 0.1
print("会员消费,享受9折优惠")
else:
if purchase_amount > 1000:
discount = 0.1
print("非会员大额消费,享受9折优惠")
else:
discount = 0
print("非会员,无折扣")
final_price = purchase_amount * (1 - discount)
print(f"最终价格: {final_price:.2f}")
# 运行基础条件判断演示
basic_condition_demo()
```
### 条件表达式与逻辑运算符
```python
# 条件表达式进阶
def advanced_conditions():
"""高级条件表达式技巧"""
# 1. 布尔运算符:and, or, not
age = 25
has_license = True
has_car = False
# 使用and运算符
if age >= 18 and has_license:
print("可以驾驶")
# 使用or运算符
if has_car or has_license:
print("与交通工具有关")
# 使用not运算符
if not has_car:
print("没有汽车")
# 2. 组合条件
income = 80000
credit_score = 750
# 复杂条件判断
if (income > 50000 and credit_score > 700) or (income > 100000):
print("符合贷款条件")
else:
print("不符合贷款条件")
# 3. 三元运算符(条件表达式)
x = 10
y = 20
# 传统写法
if x > y:
max_value = x
else:
max_value = y
# 三元运算符写法
max_value_ternary = x if x > y else y
print(f"最大值(传统): {max_value}")
print(f"最大值(三元): {max_value_ternary}")
# 4. 链式比较
number = 15
# 传统写法
if number > 10 and number < 20:
print("数字在10到20之间")
# 链式比较写法
if 10 < number < 20:
print("数字在10到20之间(链式比较)")
# 5. 成员运算符:in, not in
fruits = ["apple", "banana", "orange", "grape"]
if "apple" in fruits:
print("苹果在水果列表中")
if "pear" not in fruits:
print("梨不在水果列表中")
# 字符串检查
text = "Python编程很有趣"
if "编程" in text:
print("文本包含'编程'")
# 6. 身份运算符:is, is not
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(f"list1 is list2: {list1 is list2}") # False,不同对象
print(f"list1 is list3: {list1 is list3}") # True,同一对象
print(f"list1 == list2: {list1 == list2}") # True,值相等
# 与None比较时应使用is
value = None
if value is None:
print("值为空")
# 运行高级条件演示
advanced_conditions()
```
### 条件判断实战应用
```python
# 条件判断实战案例
def practical_condition_examples():
"""条件判断实战应用"""
print("=== 学生成绩管理系统 ===")
# 学生数据
students = [
{"name": "张三", "math": 85, "english": 90, "chinese": 88},
{"name": "李四", "math": 92, "english": 78, "chinese": 85},
{"name": "王五", "math": 76, "english": 82, "chinese": 79},
{"name": "赵六", "math": 65, "english": 70, "chinese": 72},
]
# 分析每个学生
for student in students:
name = student["name"]
math = student["math"]
english = student["english"]
chinese = student["chinese"]
# 计算平均分
average = (math + english + chinese) / 3
# 判断成绩等级
if average >= 90:
grade = "优秀"
elif average >= 80:
grade = "良好"
elif average >= 70:
grade = "中等"
elif average >= 60:
grade = "及格"
else:
grade = "不及格"
# 判断是否有偏科(单科与平均分差距大于15分)
weak_subjects = []
strong_subjects = []
if abs(math - average) > 15:
if math < average:
weak_subjects.append("数学")
else:
strong_subjects.append("数学")
if abs(english - average) > 15:
if english < average:
weak_subjects.append("英语")
else:
strong_subjects.append("英语")
if abs(chinese - average) > 15:
if chinese < average:
weak_subjects.append("语文")
else:
strong_subjects.append("语文")
# 输出结果
print(f"\n学生: {name}")
print(f" 平均分: {average:.1f}")
print(f" 等级: {grade}")
if weak_subjects:
print(f" 需要加强的科目: {', '.join(weak_subjects)}")
if strong_subjects:
print(f" 优势科目: {', '.join(strong_subjects)}")
# 特殊奖励判断
if average >= 85 and len(weak_subjects) == 0:
print(" 🎉 获得全科均衡优秀奖!")
if any(score >= 95 for score in [math, english, chinese]):
print(" ⭐ 有单科突出表现!")
print("\n=== 用户权限管理系统 ===")
# 用户角色和权限
users = [
{"username": "admin", "role": "administrator", "is_active": True},
{"username": "editor", "role": "editor", "is_active": True},
{"username": "viewer", "role": "viewer", "is_active": False},
{"username": "guest", "role": "guest", "is_active": True},
]
# 尝试的操作
attempted_operation = "delete_article"
for user in users:
username = user["username"]
role = user["role"]
is_active = user["is_active"]
# 权限检查逻辑
can_perform = False
if not is_active:
print(f"\n用户 {username}: 账户未激活,无法操作")
continue
# 基于角色的权限判断
if role == "administrator":
can_perform = True
elif role == "editor":
if attempted_operation in ["create_article", "edit_article"]:
can_perform = True
else:
can_perform = False
elif role == "viewer":
if attempted_operation == "view_article":
can_perform = True
else:
can_perform = False
else: # guest角色
can_perform = False
# 输出结果
if can_perform:
print(f"\n用户 {username} ({role}): 允许执行 {attempted_operation}")
else:
print(f"\n用户 {username} ({role}): 拒绝执行 {attempted_operation}")
# 运行实战案例
practical_condition_examples()
```
## 循环结构:for与while循环
### for循环基础与应用
```python
# for循环详解
def for_loop_demo():
"""for循环的各种用法"""
print("=== for循环基础 ===")
# 1. 遍历列表
fruits = ["apple", "banana", "orange", "grape"]
print("遍历水果列表:")
for fruit in fruits:
print(f" - {fruit}")
# 2. 遍历字符串
text = "Python"
print("\n遍历字符串:")
for char in text:
print(f" {char}")
# 3. 使用range函数
print("\n使用range生成序列:")
# range(stop)
print("range(5):", list(range(5)))
# range(start, stop)
print("range(2, 7):", list(range(2, 7)))
# range(start, stop, step)
print("range(1, 10, 2):", list(range(1, 10, 2)))
# 4. 遍历字典
student = {"name": "张三", "age": 20, "major": "计算机科学"}
print("\n遍历字典:")
for key in student:
print(f" {key}: {student[key]}")
print("\n遍历字典键值对:")
for key, value in student.items():
print(f" {key}: {value}")
# 5. 遍历集合
unique_numbers = {1, 3, 5, 7, 9}
print("\n遍历集合:")
for num in unique_numbers:
print(f" {num}")
print("\n=== for循环进阶技巧 ===")
# 6. 使用enumerate获取索引
languages = ["Python", "Java", "C++", "JavaScript"]
print("带索引的遍历:")
for index, language in enumerate(languages):
print(f" {index + 1}. {language}")
# 7. 使用zip并行遍历多个序列
names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
print("\n并行遍历:")
for name, score in zip(names, scores):
print(f" {name}: {score}分")
# 8. 使用reversed反向遍历
print("\n反向遍历:")
for fruit in reversed(fruits):
print(f" {fruit}")
# 9. 使用sorted排序遍历
numbers = [3, 1, 4, 1, 5, 9, 2]
print("\n排序遍历:")
for num in sorted(set(numbers)): # 先去重再排序
print(f" {num}")
# 10. 列表推导式中的for循环
print("\n列表推导式:")
squares = [x**2 for x in range(1, 6)]
print(f" 平方数: {squares}")
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f" 偶数平方: {even_squares}")
# 运行for循环演示
for_loop_demo()
```
### while循环与应用
```python
# while循环详解
def while_loop_demo():
"""while循环的各种用法"""
print("=== while循环基础 ===")
# 1. 基础while循环
count = 0
while count < 5:
print(f"计数: {count}")
count += 1
# 2. 使用break退出循环
print("\n使用break退出循环:")
while True:
user_input = input("请输入一个数字(输入q退出): ")
if user_input.lower() == 'q':
print("退出程序")
break
try:
number = float(user_input)
print(f"输入的数字是: {number}")
except ValueError:
print("请输入有效的数字")
<"b3.p5k3.org.cn"><"r9.p5k3.org.cn"><"k2.p5k3.org.cn">
# 3. 使用continue跳过当前迭代
print("\n使用continue跳过某些迭代:")
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # 跳过偶数
print(f"奇数: {number}")
# 4. 模拟do-while循环(Python没有do-while)
print("\n模拟do-while循环:")
# 使用while True和break模拟
while True:
user_input = input("请输入'y'继续: ")
if user_input.lower() != 'y':
break
print("继续执行...")
# 5. 复杂的while循环示例
print("\n=== while循环实战 ===")
# 猜数字游戏
import random
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("猜数字游戏开始!数字在1到100之间")
while attempts < max_attempts:
attempts += 1
remaining = max_attempts - attempts
try:
guess = int(input(f"\n第{attempts}次尝试,还剩{remaining}次: "))
except ValueError:
print("请输入有效的数字!")
continue
if guess < secret_number:
print("猜小了!")
elif guess > secret_number:
print("猜大了!")
else:
print(f"🎉 恭喜!你猜对了!数字是{secret_number}")
print(f"你用了{attempts}次尝试")
break
else:
# while-else结构:循环正常结束(非break退出)时执行
print(f"\n游戏结束!你没有猜对。正确答案是{secret_number}")
# 6. 数据处理中的while循环
print("\n=== 数据处理示例 ===")
# 从文件中读取数据直到特定条件
def process_data_stream():
"""模拟处理数据流"""
print("开始处理数据流...")
# 模拟数据流
data_stream = [10, 20, 30, 40, 50, -1, 60, 70] # -1表示结束标志
index = 0
total = 0
count = 0
while True:
if index >= len(data_stream):
print("数据流结束")
break
value = data_stream[index]
index += 1
if value == -1:
print("遇到结束标志,停止处理")
break
total += value
count += 1
print(f"处理数据: {value}, 当前总和: {total}")
if count > 0:
average = total / count
print(f"数据处理完成: 共{count}个数据,平均值: {average:.2f}")
process_data_stream()
# 运行while循环演示
while_loop_demo()
```
## 循环控制与高级技巧
```python
# 循环控制与高级技巧
def loop_control_techniques():
"""循环控制的高级技巧"""
print("=== 循环控制技巧 ===")
# 1. 循环中的else子句
def find_prime_numbers(limit):
"""查找质数"""
print(f"查找小于等于{limit}的质数:")
for num in range(2, limit + 1):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
# 这个else属于内层for循环
# 当循环正常完成(没有遇到break)时执行
print(f" {num}是质数")
<"p5.p5k3.org.cn"><"m1.p5k3.org.cn"><"a8.p5k3.org.cn">
find_prime_numbers(20)
# 2. 嵌套循环优化
def nested_loop_optimization():
"""嵌套循环的优化技巧"""
print("\n=== 矩阵操作示例 ===")
# 创建一个3x3矩阵
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("原始矩阵:")
for row in matrix:
print(f" {row}")
# 传统嵌套循环
print("\n传统遍历:")
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f" matrix[{i}][{j}] = {matrix[i][j]}")
# 更Pythonic的写法
print("\nPythonic遍历:")
for i, row in enumerate(matrix):
for j, value in enumerate(row):
print(f" matrix[{i}][{j}] = {value}")
# 3. 使用itertools模块
import itertools
print("\n=== 使用itertools ===")
# 无限循环
print("无限循环示例(限制5次):")
counter = 0
for i in itertools.count(start=1, step=2): # 从1开始,每次加2
print(f" {i}")
counter += 1
if counter >= 5:
break
# 循环多个序列的所有组合
print("\n组合示例:")
colors = ["红", "蓝", "绿"]
sizes = ["S", "M", "L"]
for color, size in itertools.product(colors, sizes):
print(f" {color}色 {size}号")
# 4. 生成器表达式与循环
print("\n=== 生成器与循环 ===")
# 生成器表达式(惰性求值)
numbers = range(1, 1000000) # 很大的范围
# 使用生成器表达式避免内存问题
even_squares = (x**2 for x in numbers if x % 2 == 0)
print("前10个偶数的平方:")
count = 0
for square in even_squares:
print(f" {square}")
count += 1
if count >= 10:
break
nested_loop_optimization()
# 5. 异常处理与循环
def exception_in_loops():
"""循环中的异常处理"""
print("\n=== 循环中的异常处理 ===")
data_list = ["10", "20", "abc", "30", "40", "def"]
valid_numbers = []
for item in data_list:
try:
number = float(item)
valid_numbers.append(number)
print(f"成功转换: {item} -> {number}")
except ValueError:
print(f"转换失败: {item} 不是有效数字")
# continue # 可以继续处理下一个
print(f"\n有效数字列表: {valid_numbers}")
if valid_numbers:
average = sum(valid_numbers) / len(valid_numbers)
print(f"平均值: {average:.2f}")
exception_in_loops()
# 6. 循环性能优化
def loop_performance():
"""循环性能优化技巧"""
print("\n=== 循环性能优化 ===")
import time
# 创建测试数据
large_list = list(range(1000000))
# 方法1:传统循环(较慢)
start_time = time.time()
total1 = 0
for num in large_list:
total1 += num
end_time = time.time()
print(f"传统循环耗时: {end_time - start_time:.4f}秒")
# 方法2:使用内置函数(更快)
start_time = time.time()
total2 = sum(large_list)
end_time = time.time()
print(f"内置sum函数耗时: {end_time - start_time:.4f}秒")
# 验证结果
print(f"总和验证: {total1 == total2}")
# 列表推导式 vs map函数
print("\n列表推导式性能对比:")
start_time = time.time()
squares1 = [x**2 for x in range(10000)]
end_time = time.time()
print(f"列表推导式耗时: {end_time - start_time:.4f}秒")
start_time = time.time()
squares2 = list(map(lambda x: x**2, range(10000)))
end_time = time.time()
print(f"map函数耗时: {end_time - start_time:.4f}秒")
loop_performance()
# 运行循环控制演示
loop_control_techniques()
```
## 流程控制综合应用
```python
# 综合应用示例
def comprehensive_application():
"""流程控制综合应用"""
print("=== 综合应用:简易库存管理系统 ===")
# 初始库存
inventory = {
"apple": {"price": 5.0, "quantity": 100, "category": "水果"},
"banana": {"price": 3.0, "quantity": 150, "category": "水果"},
"milk": {"price": 8.0, "quantity": 50, "category": "奶制品"},
"bread": {"price": 6.0, "quantity": 80, "category": "面包"},
"egg": {"price": 0.5, "quantity": 200, "category": "蛋类"},
}
# 购物车
shopping_cart = {}
def display_inventory():
"""显示库存"""
print("\n📦 当前库存:")
print("-" * 40)
for item, details in inventory.items():
print(f" {item:10} 价格: ¥{details['price']:<5} "
f"数量: {details['quantity']:<4} "
f"类别: {details['category']}")
print("-" * 40)
def add_to_cart(item, quantity):
"""添加到购物车"""
if item not in inventory:
print(f"❌ 错误:商品'{item}'不存在")
return False
if inventory[item]["quantity"] < quantity:
print(f"❌ 错误:库存不足,只剩{inventory[item]['quantity']}个")
return False
if item in shopping_cart:
shopping_cart[item] += quantity
else:
shopping_cart[item] = quantity
inventory[item]["quantity"] -= quantity
print(f"✅ 已添加 {quantity} 个 {item} 到购物车")
return True
def checkout():
"""结算"""
if not shopping_cart:
print("购物车为空")
return
print("\n💰 结算单:")
print("=" * 40)
total = 0
for item, quantity in shopping_cart.items():
price = inventory[item]["price"]
subtotal = price * quantity
total += subtotal
print(f" {item:10} × {quantity:<3} @ ¥{price:<5} = ¥{subtotal:.2f}")
print("=" * 40)
print(f"总计: ¥{total:.2f}")
# 应用折扣
discount = 0
if total > 100:
discount = total * 0.1
print(f"折扣(满100减10%): -¥{discount:.2f}")
total -= discount
print(f"应付金额: ¥{total:.2f}")
print("=" * 40)
return total
# 主程序循环
while True:
print("\n🛒 库存管理系统")
print("1. 查看库存")
print("2. 添加商品到购物车")
print("3. 查看购物车")
print("4. 结算")
print("5. 退出")
choice = input("请选择操作 (1-5): ")
if choice == "1":
display_inventory()
elif choice == "2":
display_inventory()
item = input("请输入商品名称: ").lower()
if item not in inventory:
print(f"商品'{item}'不存在")
continue
try:
quantity = int(input(f"请输入数量 (最大{inventory[item]['quantity']}): "))
if quantity <= 0:
print("数量必须大于0")
continue
add_to_cart(item, quantity)
except ValueError:
print("请输入有效的数字")
elif choice == "3":
if not shopping_cart:
print("购物车为空")
else:
print("\n🛍️ 购物车内容:")
for item, quantity in shopping_cart.items():
print(f" {item}: {quantity}个")
elif choice == "4":
total = checkout()
if total is not None:
confirm = input("确认支付?(y/n): ").lower()
if confirm == 'y':
print("✅ 支付成功!感谢您的购物")
shopping_cart.clear()
else:
print("支付取消")
elif choice == "5":
print("谢谢使用,再见!")
break
else:
print("无效选择,请重新输入")
# 运行综合应用
if __name__ == "__main__":
comprehensive_application()
```
## 总结:流程控制的最佳实践
1. **条件判断要点**:
- 使用清晰的逻辑结构,避免过深的嵌套
- 善用布尔运算符简化复杂条件
- 理解`==`与`is`的区别,正确比较对象
2. **循环结构优化**:
- 优先使用`for`循环遍历已知序列
- `while`循环适合不确定次数的迭代
- 使用`break`和`continue`控制循环流程
- 理解循环的`else`子句的特殊用途
3. **性能与可读性平衡**:
- 对于大数据集,考虑使用生成器避免内存问题
- 内置函数通常比手动循环更快
- 保持代码清晰比过度优化更重要
4. **实用技巧**:
- 使用`enumerate`获取索引和值
- 使用`zip`并行遍历多个序列
- 利用列表推导式简化代码
- 在循环中妥善处理异常
掌握Python的流程控制不仅能让代码正确运行,更能让代码表达清晰的逻辑意图。通过不断练习和应用这些概念,你将能编写出更加优雅、高效和可维护的Python程序。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3109509/ ,如需转载,请注明出处,否则将追究法律责任。