
流程控制语句用于控制程序的执行顺序,Python 提供了丰富的流程控制结构,包括条件判断、循环控制、循环中断等。
一、流程控制

二、条件判断语句
1. if 语句
age = 18
if age >= 18:
print("成年人")
2. if-else 语句
score = 85
if score >= 60:
print("及格")
else:
print("不及格")
3. if-elif-else 语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"等级: {grade}") # 等级: B
4. 嵌套 if 语句
age = 25
has_license = True
if age >= 18:
if has_license:
print("可以开车")
else:
print("需要考驾照")
else:
print("未成年不能开车")
5. 条件表达式(三元运算符)
# 语法:值1 if 条件 else 值2
age = 20
status = "成年人" if age >= 18 else "未成年人"
print(status) # 成年人
# 实际应用
max_value = a if a > b else b
三、循环控制语句
1. for 循环
遍历序列
# 遍历列表
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit)
# 遍历字符串
for char in "Python":
print(char)
# 遍历字典
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key}: {value}")
使用 range() 函数
# range(stop): 0 到 stop-1
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop): start 到 stop-1
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# range(start, stop, step): 指定步长
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# 倒序
for i in range(10, 0, -1):
print(i) # 10, 9, 8, ..., 1
遍历索引和值
# 使用 enumerate()
colors = ["红", "绿", "蓝"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# 指定起始索引
for index, color in enumerate(colors, start=1):
print(f"{index}: {color}")
并行遍历
# 使用 zip()
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} {age}岁")
# 不等长时自动截断
a = [1, 2, 3]
b = ['a', 'b']
for x, y in zip(a, b):
print(x, y) # (1, 'a'), (2, 'b')(3 被忽略)
# 使用 zip_longest 保留所有元素
from itertools import zip_longest
for x, y in zip_longest(a, b, fillvalue=None):
print(x, y) # (1, 'a'), (2, 'b'), (3, None)
2. while 循环
基本用法
# 计数循环
count = 0
while count < 5:
print(count)
count += 1
# 无限循环(需要 break 退出)
while True:
user_input = input("输入 'quit' 退出: ")
if user_input == 'quit':
break
print(f"你输入了: {user_input}")
四、循环中断语句
1. break - 跳出循环
# 查找第一个偶数
numbers = [1, 3, 5, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(f"找到偶数: {num}")
break # 找到后立即退出循环
else:
print("没有找到偶数") # 循环正常结束才执行
# 输出: 找到偶数: 8
2. continue - 跳过本次循环
# 打印奇数
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i) # 1, 3, 5, 7, 9
# 过滤掉空字符串
words = ["hello", "", "world", "", "python"]
for word in words:
if not word:
continue
print(word.upper())
3. pass - 占位符
# 用于语法上需要但什么都不做的场景
def future_function():
pass # 稍后实现
class MyClass:
pass # 空类
# 条件中的占位
if condition:
pass # 暂不处理
else:
do_something()
五、循环嵌套
1. 嵌套 for 循环
# 打印乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print() # 换行
# 输出:
# 1×1=1
# 1×2=2 2×2=4
# 1×3=3 2×3=6 3×3=9
# ...
2. 嵌套 while 循环
# 打印三角形
i = 1
while i <= 5:
j = 1
while j <= i:
print("*", end="")
j += 1
print()
i += 1
3. 跳出多层循环
# 方法1:使用标志变量
found = False
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
found = True
break
if found:
break
# 方法2:使用 else-continue(不推荐)
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
break
else:
continue
break
# 方法3:封装为函数(最推荐)
def find_element():
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
return (i, j)
return None
result = find_element()
核心要点:
-
条件判断注意缩进(4个空格)
-
循环注意避免无限循环
-
break只跳出最内层循环 -
while循环记得更新条件变量