循环语句 #

循环语句用于重复执行一段代码。

一、while循环 #

1.1 基本语法 #

python
# 基本while循环
count = 0
while count < 5:
    print(count)
    count += 1
# 输出:0 1 2 3 4

1.2 循环条件 #

python
# 条件为假时停止
x = 10
while x > 0:
    print(x)
    x -= 1

# 无限循环(需要break退出)
while True:
    response = input("输入q退出:")
    if response == 'q':
        break

1.3 while-else #

python
# else在循环正常结束时执行
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("循环结束")
# 输出:0 1 2 循环结束

# break会跳过else
count = 0
while count < 3:
    if count == 1:
        break
    print(count)
    count += 1
else:
    print("不会执行")  # 被break跳过
# 输出:0

二、for循环 #

2.1 基本语法 #

python
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "Hello":
    print(char)

# 遍历字典
person = {"name": "Tom", "age": 25}
for key in person:
    print(key)  # 遍历键

for key, value in person.items():
    print(f"{key}: {value}")  # 遍历键值对

for value in person.values():
    print(value)  # 遍历值

2.2 range函数 #

python
# range(stop)
for i in range(5):
    print(i)  # 0 1 2 3 4

# range(start, stop)
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

# 反向range
for i in range(5, 0, -1):
    print(i)  # 5 4 3 2 1

# 创建列表
numbers = list(range(5))
print(numbers)  # [0, 1, 2, 3, 4]

2.3 enumerate #

python
# 同时获取索引和值
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 输出:
# 0: 苹果
# 1: 香蕉
# 2: 橙子

# 指定起始索引
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}")
# 输出:1: 苹果, 2: 香蕉, 3: 橙子

2.4 zip #

python
# 并行遍历多个序列
names = ["Tom", "Jerry", "Alice"]
ages = [25, 30, 28]

for name, age in zip(names, ages):
    print(f"{name}: {age}岁")
# 输出:
# Tom: 25岁
# Jerry: 30岁
# Alice: 28岁

# 不同长度时以最短的为准
a = [1, 2, 3, 4]
b = ['a', 'b', 'c']
for x, y in zip(a, b):
    print(x, y)
# 输出:1 a, 2 b, 3 c

# 创建字典
keys = ['name', 'age', 'city']
values = ['Tom', 25, 'Beijing']
person = dict(zip(keys, values))
print(person)  # {'name': 'Tom', 'age': 25, 'city': 'Beijing'}

2.5 for-else #

python
# else在循环正常结束时执行
for i in range(3):
    print(i)
else:
    print("循环结束")
# 输出:0 1 2 循环结束

# break会跳过else
for i in range(5):
    if i == 2:
        break
    print(i)
else:
    print("不会执行")
# 输出:0 1

三、循环控制 #

3.1 break #

python
# 跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)
# 输出:0 1 2 3 4

# 嵌套循环中只跳出内层
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(f"({i}, {j})")
# 输出:(0, 0), (1, 0), (2, 0)

3.2 continue #

python
# 跳过当前迭代
for i in range(5):
    if i == 2:
        continue
    print(i)
# 输出:0 1 3 4

# 过滤数据
numbers = [1, -2, 3, -4, 5]
for n in numbers:
    if n < 0:
        continue
    print(n)
# 输出:1 3 5

3.3 嵌套循环 #

python
# 嵌套for循环
for i in range(3):
    for j in range(3):
        print(f"({i}, {j})", end=' ')
    print()
# 输出:
# (0, 0) (0, 1) (0, 2)
# (1, 0) (1, 1) (1, 2)
# (2, 0) (2, 1) (2, 2)

# 九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}×{i}={i*j}", end=' ')
    print()

四、循环技巧 #

4.1 遍历并修改 #

python
# 错误方式:遍历时修改列表
# numbers = [1, 2, 3, 4, 5]
# for n in numbers:
#     if n % 2 == 0:
#         numbers.remove(n)  # 可能出问题

# 正确方式:创建新列表
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0]

# 或遍历副本
numbers = [1, 2, 3, 4, 5]
for n in numbers[:]:
    if n % 2 == 0:
        numbers.remove(n)
print(numbers)  # [1, 3, 5]

4.2 反向遍历 #

python
# 反向遍历列表
items = ['a', 'b', 'c']
for item in reversed(items):
    print(item)
# 输出:c b a

# 反向range
for i in range(10, 0, -1):
    print(i)

4.3 排序遍历 #

python
# 排序后遍历
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
for n in sorted(numbers):
    print(n, end=' ')
print()  # 1 1 2 3 4 5 6 9

# 反向排序
for n in sorted(numbers, reverse=True):
    print(n, end=' ')
print()  # 9 6 5 4 3 2 1 1

# 按条件排序
words = ['banana', 'pie', 'apple', 'cherry']
for word in sorted(words, key=len):
    print(word, end=' ')
print()  # pie apple banana cherry

4.4 同时遍历索引和值 #

python
items = ['a', 'b', 'c']

# 方法1:enumerate
for i, item in enumerate(items):
    print(f"{i}: {item}")

# 方法2:range + len
for i in range(len(items)):
    print(f"{i}: {items[i]}")

# 推荐使用enumerate

4.5 遍历字典 #

python
person = {"name": "Tom", "age": 25, "city": "Beijing"}

# 遍历键
for key in person:
    print(key)

# 遍历键(显式)
for key in person.keys():
    print(key)

# 遍历值
for value in person.values():
    print(value)

# 遍历键值对
for key, value in person.items():
    print(f"{key}: {value}")

五、常见模式 #

5.1 查找元素 #

python
# 查找第一个满足条件的元素
def find_first(items, condition):
    for item in items:
        if condition(item):
            return item
    return None

numbers = [1, 3, 5, 7, 8, 9]
first_even = find_first(numbers, lambda x: x % 2 == 0)
print(first_even)  # 8

# 使用for-else
def find_index(items, target):
    for i, item in enumerate(items):
        if item == target:
            return i
    return -1

5.2 计数 #

python
# 计数满足条件的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_count = sum(1 for n in numbers if n % 2 == 0)
print(even_count)  # 4

# 传统方式
count = 0
for n in numbers:
    if n % 2 == 0:
        count += 1

5.3 分组 #

python
# 按条件分组
from collections import defaultdict

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
groups = defaultdict(list)

for n in numbers:
    key = "偶数" if n % 2 == 0 else "奇数"
    groups[key].append(n)

print(dict(groups))  # {'奇数': [1, 3, 5, 7, 9], '偶数': [2, 4, 6, 8]}

5.4 累积计算 #

python
# 累积求和
total = 0
for n in range(1, 101):
    total += n
print(total)  # 5050

# 使用sum
total = sum(range(1, 101))

# 累积乘积
import math
product = 1
for n in range(1, 6):
    product *= n
print(product)  # 120

# 使用math.prod(Python 3.8+)
product = math.prod(range(1, 6))

六、常见陷阱 #

6.1 无限循环 #

python
# 忘记更新循环变量
# count = 0
# while count < 5:
#     print(count)  # 无限循环!
#     # 忘记 count += 1

# 正确写法
count = 0
while count < 5:
    print(count)
    count += 1

6.2 遍历时修改 #

python
# 遍历时删除元素(可能跳过元素)
numbers = [1, 2, 3, 4, 5]
# for n in numbers:
#     if n % 2 == 0:
#         numbers.remove(n)  # 危险!

# 正确方式
numbers = [n for n in numbers if n % 2 != 0]

6.3 浮点数循环 #

python
# 浮点数循环可能有精度问题
# i = 0.0
# while i != 1.0:
#     i += 0.1  # 可能无限循环

# 正确方式
i = 0.0
while i < 1.0:
    i += 0.1
    print(i)

# 或使用整数
for i in range(10):
    value = i * 0.1
    print(value)

6.4 可变默认参数 #

python
# 不要在循环中使用可变默认参数
def add_item(item, items=[]):
    items.append(item)
    return items

# 每次调用都会累积
print(add_item(1))  # [1]
print(add_item(2))  # [1, 2]

# 正确方式
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

七、性能优化 #

7.1 使用内置函数 #

python
# 使用内置函数代替循环
numbers = [1, 2, 3, 4, 5]

# 求和
total = sum(numbers)  # 代替循环累加

# 查找最大/最小
max_value = max(numbers)
min_value = min(numbers)

# 判断存在
has_even = any(n % 2 == 0 for n in numbers)
all_positive = all(n > 0 for n in numbers)

7.2 使用生成器 #

python
# 大数据量时使用生成器
def large_data():
    for i in range(1000000):
        yield i

# 不会一次性创建大列表
for item in large_data():
    process(item)

7.3 避免不必要的循环 #

python
# 使用in代替循环查找
items = [1, 2, 3, 4, 5]

# 不推荐
found = False
for item in items:
    if item == 3:
        found = True
        break

# 推荐
found = 3 in items

八、总结 #

循环类型 用途
while 不确定次数的循环
for 遍历序列
range() 生成数字序列
enumerate() 获取索引和值
zip() 并行遍历
控制语句 用途
break 跳出循环
continue 跳过当前迭代
else 循环正常结束后执行

最佳实践:

  • 优先使用 for 遍历序列
  • 使用 enumerate 获取索引
  • 避免遍历时修改序列
  • 使用内置函数优化性能
最后更新:2026-03-16