控制结构是编程语言中用来控制程序执行流程的语句。Python提供了条件语句、循环语句等控制结构,让程序能够根据不同条件执行不同的代码块。
程序执行流程图:
┌─────────────────────────────────────────────┐
│ 程序控制流程 │
├─────────────────────────────────────────────┤
│ │
│ 顺序执行 ──→ 条件分支 ──→ 循环重复 │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ 语句1 if/elif for/while │
│ 语句2 else break │
│ 语句3 continue │
│ │
└─────────────────────────────────────────────┘
条件语句(if, elif, else)
条件语句允许程序根据条件的真假来选择不同的执行路径。
1. 基本if语句
# 基本if语句
age = 18if age >= 18:print("你已经成年了!")print("可以投票和工作")print("程序继续执行")# 带else的if语句
score = 85if score >= 60:print("考试及格!")
else:print("考试不及格,需要补考")# 嵌套if语句
weather = "晴天"
temperature = 25if weather == "晴天":print("天气不错!")if temperature > 30:print("有点热,记得防晒")elif temperature < 10:print("有点冷,多穿点衣服")else:print("温度刚好,适合出门")
else:print("天气不太好")
2. elif语句(多重条件)
# 成绩等级判断
score = 92if score >= 90:grade = "A"comment = "优秀"
elif score >= 80:grade = "B"comment = "良好"
elif score >= 70:grade = "C"comment = "中等"
elif score >= 60:grade = "D"comment = "及格"
else:grade = "F"comment = "不及格"print(f"分数: {score}, 等级: {grade}, 评价: {comment}")# 多条件判断
username = "admin"
password = "123456"
is_active = Trueif username == "admin" and password == "123456" and is_active:print("登录成功!")
elif not is_active:print("账户已被禁用")
elif username != "admin":print("用户名错误")
else:print("密码错误")
3. 条件表达式(三元运算符)
# 传统写法
age = 20
if age >= 18:status = "成年人"
else:status = "未成年人"
print(f"状态: {status}")# 条件表达式(三元运算符)
age = 16
status = "成年人" if age >= 18 else "未成年人"
print(f"状态: {status}")# 更复杂的条件表达式
score = 85
result = "优秀" if score >= 90 else "良好" if score >= 80 else "及格" if score >= 60 else "不及格"
print(f"成绩: {score}, 评价: {result}")# 实际应用示例
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x if x % 2 == 0 else 0 for x in numbers]
print(f"偶数或0: {even_numbers}")
4. 条件语句的最佳实践
# ✅ 好的写法:使用in操作符
day = "星期六"
if day in ["星期六", "星期日"]:print("今天是周末")# ❌ 不好的写法
# if day == "星期六" or day == "星期日":
# print("今天是周末")# ✅ 好的写法:利用布尔值的特性
name = ""
if not name: # 空字符串为Falseprint("请输入姓名")# ❌ 不好的写法
# if name == "":
# print("请输入姓名")# ✅ 好的写法:使用is比较None
value = None
if value is None:print("值为空")# ❌ 不好的写法
# if value == None:
# print("值为空")# ✅ 好的写法:避免深层嵌套
def process_user(user):if not user:return "用户不存在"if not user.get("active"):return "用户未激活"if user.get("age", 0) < 18:return "用户未成年"return "用户验证通过"# 测试
user1 = {"name": "张三", "age": 25, "active": True}
user2 = {"name": "李四", "age": 16, "active": True}
user3 = Noneprint(process_user(user1))
print(process_user(user2))
print(process_user(user3))
循环语句
循环语句允许重复执行一段代码,直到满足某个条件为止。
1. for循环
for循环用于遍历序列(如列表、元组、字符串)或其他可迭代对象。
# 遍历列表
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
print("水果清单:")
for fruit in fruits:print(f"- {fruit}")# 遍历字符串
word = "Python"
print("\n字母分解:")
for char in word:print(f"字母: {char}")# 遍历字典
student = {"姓名": "张三", "年龄": 20, "专业": "计算机科学"}
print("\n学生信息:")
for key, value in student.items():print(f"{key}: {value}")# 只遍历键
print("\n只显示键:")
for key in student.keys():print(key)# 只遍历值
print("\n只显示值:")
for value in student.values():print(value)
2. range()函数
# 基本用法
print("0到4:")
for i in range(5):print(i, end=" ")
print()# 指定起始和结束
print("\n1到5:")
for i in range(1, 6):print(i, end=" ")
print()# 指定步长
print("\n偶数0到10:")
for i in range(0, 11, 2):print(i, end=" ")
print()# 倒序
print("\n倒数5到1:")
for i in range(5, 0, -1):print(i, end=" ")
print()# 实际应用:打印乘法表
print("\n九九乘法表:")
for i in range(1, 10):for j in range(1, i + 1):print(f"{j}×{i}={i*j:2d}", end=" ")print() # 换行
3. enumerate()函数
# 获取索引和值
fruits = ["苹果", "香蕉", "橙子"]
print("带索引的遍历:")
for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")# 指定起始索引
print("\n从1开始编号:")
for index, fruit in enumerate(fruits, start=1):print(f"第{index}个水果: {fruit}")# 实际应用:处理文件行号
lines = ["第一行内容", "第二行内容", "第三行内容"]
for line_num, content in enumerate(lines, start=1):print(f"行{line_num}: {content}")
4. zip()函数
# 同时遍历多个序列
names = ["张三", "李四", "王五"]
ages = [20, 25, 30]
cities = ["北京", "上海", "广州"]print("学生信息:")
for name, age, city in zip(names, ages, cities):print(f"{name}, {age}岁, 来自{city}")# 长度不同的序列
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']
print("\n长度不同的序列:")
for num, letter in zip(list1, list2):print(f"{num} - {letter}")# 创建字典
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
person = dict(zip(keys, values))
print(f"\n创建的字典: {person}")# 矩阵转置
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(f"\n原矩阵: {matrix}")
print(f"转置后: {list(transposed)}")
5. while循环
while循环在条件为真时重复执行代码块。
# 基本while循环
count = 0
print("倒计时:")
while count < 5:print(f"{5 - count}...")count += 1
print("发射!")# 用户输入循环
print("\n猜数字游戏:")
import random
target = random.randint(1, 100)
guess_count = 0
max_guesses = 7print(f"我想了一个1到100之间的数字,你有{max_guesses}次机会猜中它!")while guess_count < max_guesses:try:guess = int(input(f"第{guess_count + 1}次猜测,请输入数字: "))guess_count += 1if guess == target:print(f"恭喜!你猜中了!数字是{target}")breakelif guess < target:print("太小了!")else:print("太大了!")if guess_count == max_guesses:print(f"游戏结束!正确答案是{target}")except ValueError:print("请输入有效的数字!")# 无限循环(需要break退出)
print("\n简单计算器(输入'quit'退出):")
while True:user_input = input("请输入表达式(如: 2+3)或'quit': ")if user_input.lower() == 'quit':print("再见!")breaktry:result = eval(user_input) # 注意:实际项目中不建议使用evalprint(f"结果: {result}")except:print("无效的表达式!")
循环控制(break, continue, pass)
1. break语句
break用于完全退出循环。
# 在for循环中使用break
print("查找第一个偶数:")
numbers = [1, 3, 5, 8, 9, 10, 11]
for num in numbers:if num % 2 == 0:print(f"找到第一个偶数: {num}")breakprint(f"{num}是奇数")# 在嵌套循环中使用break
print("\n在矩阵中查找特定值:")
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
found = Falsefor i, row in enumerate(matrix):for j, value in enumerate(row):if value == target:print(f"在位置({i}, {j})找到{target}")found = Truebreakif found:break# 使用标志变量的替代方案
def find_in_matrix(matrix, target):for i, row in enumerate(matrix):for j, value in enumerate(row):if value == target:return i, jreturn Noneposition = find_in_matrix(matrix, 8)
if position:print(f"数字8在位置{position}")
else:print("未找到数字8")
2. continue语句
continue用于跳过当前迭代,继续下一次迭代。
# 跳过偶数,只打印奇数
print("只打印奇数:")
for i in range(1, 11):if i % 2 == 0:continue # 跳过偶数print(i, end=" ")
print()# 处理列表,跳过无效数据
data = [1, -2, 3, 0, -5, 6, 7, -8]
positive_sum = 0
print("\n处理数据(跳过负数和零):")
for num in data:if num <= 0:print(f"跳过: {num}")continuepositive_sum += numprint(f"累加: {num}, 当前和: {positive_sum}")print(f"正数总和: {positive_sum}")# 在while循环中使用continue
print("\n输入验证(跳过无效输入):")
valid_inputs = []
count = 0while len(valid_inputs) < 3:count += 1user_input = input(f"请输入第{count}个正整数: ")try:num = int(user_input)if num <= 0:print("请输入正整数!")continuevalid_inputs.append(num)print(f"有效输入: {num}")except ValueError:print("请输入数字!")continueprint(f"收集到的有效输入: {valid_inputs}")
3. pass语句
pass是一个空操作,用作占位符。
# 作为占位符
def future_function():pass # 暂时不实现,避免语法错误class FutureClass:pass # 暂时不实现# 在条件语句中使用
age = 25
if age < 18:pass # 暂时不处理未成年情况
elif age >= 65:print("享受老年优惠")
else:print("正常价格")# 在异常处理中使用
data = [1, 2, "invalid", 4, 5]
processed = []for item in data:try:result = int(item) * 2processed.append(result)except ValueError:pass # 忽略无效数据print(f"处理后的数据: {processed}")# 调试时的临时代码
def debug_function(x):if x < 0:pass # TODO: 处理负数情况return x * 2print(debug_function(5))
4. else子句在循环中的使用
Python的循环可以有else子句,当循环正常结束(没有被break中断)时执行。
# for循环的else子句
print("查找质数:")
def is_prime(n):if n < 2:return Falsefor i in range(2, int(n ** 0.5) + 1):if n % i == 0:print(f"{n}不是质数,因为{i} × {n//i} = {n}")return Falseelse:print(f"{n}是质数")return True# 测试
test_numbers = [17, 18, 19, 20]
for num in test_numbers:is_prime(num)print()# while循环的else子句
print("密码验证(最多3次机会):")
correct_password = "python123"
attempts = 0
max_attempts = 3while attempts < max_attempts:password = input(f"请输入密码(第{attempts + 1}次尝试): ")attempts += 1if password == correct_password:print("密码正确,登录成功!")breakelse:print("密码错误")
else:print("尝试次数过多,账户被锁定!")
推导式(Comprehensions)
推导式是Python的一个强大特性,可以用简洁的语法创建列表、字典和集合。
1. 列表推导式
# 基本语法:[expression for item in iterable]
# 创建平方数列表
squares = [x**2 for x in range(1, 6)]
print(f"平方数: {squares}")# 等价的传统写法
squares_traditional = []
for x in range(1, 6):squares_traditional.append(x**2)
print(f"传统写法: {squares_traditional}")# 带条件的列表推导式
# 语法:[expression for item in iterable if condition]
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"偶数的平方: {even_squares}")# 字符串处理
words = ["hello", "world", "python", "programming"]
uppercase_words = [word.upper() for word in words]
long_words = [word for word in words if len(word) > 5]
print(f"大写单词: {uppercase_words}")
print(f"长单词: {long_words}")# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(f"展平矩阵: {flattened}")# 等价的传统写法
flattened_traditional = []
for row in matrix:for num in row:flattened_traditional.append(num)
print(f"传统写法: {flattened_traditional}")# 复杂的列表推导式
sentences = ["Hello World", "Python Programming", "Data Science"]
word_lengths = [[len(word) for word in sentence.split()] for sentence in sentences]
print(f"单词长度: {word_lengths}")
2. 字典推导式
# 基本语法:{key_expr: value_expr for item in iterable}
# 创建平方数字典
squares_dict = {x: x**2 for x in range(1, 6)}
print(f"平方数字典: {squares_dict}")# 从两个列表创建字典
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
people = {name: age for name, age in zip(names, ages)}
print(f"人员信息: {people}")# 带条件的字典推导式
even_squares_dict = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(f"偶数平方字典: {even_squares_dict}")# 字符串处理
words = ["apple", "banana", "cherry", "date"]
word_lengths = {word: len(word) for word in words}
long_words_dict = {word: len(word) for word in words if len(word) > 5}
print(f"单词长度: {word_lengths}")
print(f"长单词: {long_words_dict}")# 转换现有字典
original_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
# 键值互换
swapped_dict = {value: key for key, value in original_dict.items()}
print(f"键值互换: {swapped_dict}")# 过滤和转换
filtered_dict = {key: value * 2 for key, value in original_dict.items() if value % 2 == 0}
print(f"偶数值翻倍: {filtered_dict}")
3. 集合推导式
# 基本语法:{expression for item in iterable}
# 创建平方数集合
squares_set = {x**2 for x in range(1, 6)}
print(f"平方数集合: {squares_set}")# 去重
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]
unique_numbers = {x for x in numbers}
print(f"去重后: {unique_numbers}")# 字符串去重
text = "hello world"
unique_chars = {char for char in text if char != ' '}
print(f"唯一字符: {unique_chars}")# 数学集合操作
set_a = {x for x in range(1, 11) if x % 2 == 0} # 偶数
set_b = {x for x in range(1, 11) if x % 3 == 0} # 3的倍数
print(f"偶数集合: {set_a}")
print(f"3的倍数集合: {set_b}")
print(f"交集: {set_a & set_b}")
print(f"并集: {set_a | set_b}")
4. 生成器表达式
生成器表达式类似列表推导式,但使用圆括号,返回生成器对象。
# 生成器表达式
squares_gen = (x**2 for x in range(1, 6))
print(f"生成器对象: {squares_gen}")
print(f"生成器类型: {type(squares_gen)}")# 遍历生成器
print("生成器内容:")
for square in squares_gen:print(square, end=" ")
print()# 生成器只能遍历一次
print("再次遍历生成器:")
for square in squares_gen:print(square, end=" ") # 不会输出任何内容
print("(空的,因为生成器已耗尽)")# 内存效率比较
import sys# 列表推导式(占用更多内存)
list_comp = [x**2 for x in range(1000)]
print(f"列表推导式内存: {sys.getsizeof(list_comp)} 字节")# 生成器表达式(占用很少内存)
gen_expr = (x**2 for x in range(1000))
print(f"生成器表达式内存: {sys.getsizeof(gen_expr)} 字节")# 实际应用:处理大文件
def process_large_file(filename):"""使用生成器处理大文件"""with open(filename, 'r') as file:# 生成器表达式,逐行处理,不会一次性加载整个文件processed_lines = (line.strip().upper() for line in file if line.strip())return processed_lines# 数学应用:无限序列
def fibonacci_gen():"""斐波那契数列生成器"""a, b = 0, 1while True:yield aa, b = b, a + b# 获取前10个斐波那契数
fib_gen = fibonacci_gen()
first_10_fib = [next(fib_gen) for _ in range(10)]
print(f"前10个斐波那契数: {first_10_fib}")
实际应用示例
1. 数据处理
# 学生成绩处理系统
students = [{"name": "张三", "scores": [85, 92, 78, 96]},{"name": "李四", "scores": [76, 88, 92, 84]},{"name": "王五", "scores": [95, 87, 91, 89]},{"name": "赵六", "scores": [68, 72, 75, 70]}
]print("学生成绩分析:")
print("=" * 40)for student in students:name = student["name"]scores = student["scores"]# 计算平均分average = sum(scores) / len(scores)# 判断等级if average >= 90:grade = "优秀"elif average >= 80:grade = "良好"elif average >= 70:grade = "中等"elif average >= 60:grade = "及格"else:grade = "不及格"print(f"{name}: 平均分 {average:.1f}, 等级 {grade}")# 找出最高分和最低分max_score = max(scores)min_score = min(scores)print(f" 最高分: {max_score}, 最低分: {min_score}")# 统计各分数段excellent = sum(1 for score in scores if score >= 90)good = sum(1 for score in scores if 80 <= score < 90)average_count = sum(1 for score in scores if 70 <= score < 80)poor = sum(1 for score in scores if score < 70)print(f" 分数分布 - 优秀:{excellent}, 良好:{good}, 中等:{average_count}, 较差:{poor}")print()# 班级统计
all_scores = [score for student in students for score in student["scores"]]
class_average = sum(all_scores) / len(all_scores)
print(f"班级平均分: {class_average:.1f}")# 找出班级最高分学生
best_student = max(students, key=lambda s: sum(s["scores"]) / len(s["scores"]))
print(f"班级第一名: {best_student['name']}")
2. 文本处理
# 文本分析工具
def analyze_text(text):"""分析文本的各种统计信息"""print(f"原文本: {text}")print("=" * 50)# 基本统计char_count = len(text)word_count = len(text.split())sentence_count = text.count('.') + text.count('!') + text.count('?')print(f"字符数: {char_count}")print(f"单词数: {word_count}")print(f"句子数: {sentence_count}")# 字符频率统计char_freq = {}for char in text.lower():if char.isalpha():char_freq[char] = char_freq.get(char, 0) + 1print("\n字符频率(前5个):")sorted_chars = sorted(char_freq.items(), key=lambda x: x[1], reverse=True)for char, freq in sorted_chars[:5]:print(f" {char}: {freq}次")# 单词频率统计words = text.lower().split()word_freq = {}for word in words:# 去除标点符号clean_word = ''.join(char for char in word if char.isalnum())if clean_word:word_freq[clean_word] = word_freq.get(clean_word, 0) + 1print("\n单词频率(前5个):")sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)for word, freq in sorted_words[:5]:print(f" {word}: {freq}次")# 查找长单词long_words = [word for word in words if len(word) > 6]print(f"\n长单词(>6字符): {len(long_words)}个")if long_words:print(f" 示例: {', '.join(long_words[:3])}")# 测试文本分析
sample_text = """
Python is a powerful programming language.
It is easy to learn and has a simple syntax.
Python is widely used in data science, web development, and automation.
"""analyze_text(sample_text)
3. 游戏开发
# 简单的猜数字游戏
import randomdef number_guessing_game():"""数字猜测游戏"""print("欢迎来到猜数字游戏!")print("我想了一个1到100之间的数字,请你来猜!")# 游戏设置target_number = random.randint(1, 100)max_attempts = 7attempts = 0guessed_numbers = []print(f"你有{max_attempts}次机会猜中这个数字。")print("输入'hint'获取提示,输入'quit'退出游戏。")while attempts < max_attempts:# 显示当前状态remaining = max_attempts - attemptsprint(f"\n剩余机会: {remaining}")if guessed_numbers:print(f"已猜过的数字: {sorted(guessed_numbers)}")# 获取用户输入user_input = input("请输入你的猜测: ").strip().lower()# 处理特殊命令if user_input == 'quit':print(f"游戏结束!正确答案是 {target_number}")returnelif user_input == 'hint':# 提供提示if target_number % 2 == 0:print("提示: 这是一个偶数")else:print("提示: 这是一个奇数")continue# 验证输入try:guess = int(user_input)except ValueError:print("请输入有效的数字!")continueif guess < 1 or guess > 100:print("请输入1到100之间的数字!")continueif guess in guessed_numbers:print("你已经猜过这个数字了!")continue# 处理猜测attempts += 1guessed_numbers.append(guess)if guess == target_number:print(f"\n🎉 恭喜你!猜中了!")print(f"正确答案是 {target_number}")print(f"你用了 {attempts} 次机会")# 评价表现if attempts <= 3:print("太厉害了!你是猜数字高手!")elif attempts <= 5:print("不错的表现!")else:print("终于猜中了!")returnelif guess < target_number:print("太小了!试试更大的数字")# 给出范围提示larger_guesses = [n for n in guessed_numbers if n < target_number]if larger_guesses:min_range = max(larger_guesses) + 1print(f"提示: 答案在 {min_range} 到 100 之间")else:print("太大了!试试更小的数字")# 给出范围提示smaller_guesses = [n for n in guessed_numbers if n > target_number]if smaller_guesses:max_range = min(smaller_guesses) - 1print(f"提示: 答案在 1 到 {max_range} 之间")# 游戏失败print(f"\n😞 很遗憾,你没有在{max_attempts}次机会内猜中!")print(f"正确答案是 {target_number}")print("再试一次吧!")# 运行游戏
# number_guessing_game()
性能优化技巧
import time# 1. 列表推导式 vs 传统循环
def compare_list_creation():"""比较不同创建列表的方法的性能"""n = 100000# 方法1:传统for循环start = time.time()result1 = []for i in range(n):if i % 2 == 0:result1.append(i * 2)time1 = time.time() - start# 方法2:列表推导式start = time.time()result2 = [i * 2 for i in range(n) if i % 2 == 0]time2 = time.time() - start# 方法3:filter + mapstart = time.time()result3 = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, range(n))))time3 = time.time() - startprint(f"传统循环: {time1:.4f}秒")print(f"列表推导式: {time2:.4f}秒")print(f"filter+map: {time3:.4f}秒")print(f"列表推导式比传统循环快 {time1/time2:.1f} 倍")# 2. 成员检测:list vs set
def compare_membership_test():"""比较列表和集合的成员检测性能"""data = list(range(10000))data_set = set(data)search_items = [1000, 5000, 9999]# 列表查找start = time.time()for item in search_items * 1000: # 重复1000次result = item in datalist_time = time.time() - start# 集合查找start = time.time()for item in search_items * 1000: # 重复1000次result = item in data_setset_time = time.time() - startprint(f"列表查找: {list_time:.4f}秒")print(f"集合查找: {set_time:.4f}秒")print(f"集合比列表快 {list_time/set_time:.1f} 倍")print("性能比较:")
print("=" * 30)
compare_list_creation()
print()
compare_membership_test()
总结
本章详细介绍了Python的控制结构:
- 条件语句: if、elif、else,用于程序分支
- 循环语句: for和while,用于重复执行代码
- 循环控制: break、continue、pass,用于控制循环流程
- 推导式: 列表、字典、集合推导式,提供简洁的数据处理方式
控制结构使用指南:
┌─────────────────────────────────────────────┐
│ 何时使用哪种控制结构 │
├─────────────────────────────────────────────┤
│ if语句: │
│ • 根据条件执行不同代码 │
│ • 数据验证和错误处理 │
│ │
│ for循环: │
│ • 遍历已知序列 │
│ • 执行固定次数的操作 │
│ │
│ while循环: │
│ • 条件未知时的重复执行 │
│ • 用户交互和事件处理 │
│ │
│ 推导式: │
│ • 简洁的数据转换 │
│ • 过滤和映射操作 │
│ • 性能要求较高的场景 │
└─────────────────────────────────────────────┘
掌握这些控制结构是编写高效Python程序的基础,它们让程序能够处理复杂的逻辑和数据操作。
下一章预告: 函数与模块 - 学习如何定义函数、参数传递、作用域和模块化编程。