跳转至

03 循环语句

python循环语句详解

for循环:遍历序列与迭代控制

for循环用于遍历可迭代对象(如列表、元组、字符串等),语法简洁且高效:

for item in sequence:
    # 执行的代码块
示例:遍历列表并打印元素
1
2
3
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

通过range()函数生成数字序列,常用于控制循环次数:

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

for i in range(1,5):  # 注意range是左闭右开的,且左边界不填默认为0
    print(i)  # 因此这样子输出的就是1到4

接下来我们看一个复杂一点的案例

1
2
3
4
5
6
# 定义一个包含不同数据类型的元组
my_tuple = (10, "Hello", 3.14, True, [1, 2, 3])
# 使用for循环遍历元组
for index, element in enumerate(my_tuple):
    # 打印元素索引、值和类型信息
    print(f"索引 {index}: 值={element}, 类型={type(element)}")
1
2
3
4
5
索引 0: 值=10, 类型=<class 'int'>
索引 1: 值=Hello, 类型=<class 'str'>
索引 2: 值=3.14, 类型=<class 'float'>
索引 3: 值=True, 类型=<class 'bool'>
索引 4: 值=[1, 2, 3], 类型=<class 'list'>

其中enumerate函数是Python内置的一个实用函数,可以同时返回一个可迭代对象(如元组、列表、字符串等)的下标索引和对应元素值。其基本用法为:

enumerate(iterable, start=0)
  • iterable:要枚举的可迭代对象
  • start:索引起始值,默认为0

具体使用示例:

1.基本用法:

1
2
3
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(index, fruit)
1
2
3
0 apple
1 banana
2 orange

2.指定起始索引:

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
1
2
3
1 apple
2 banana
3 orange

3.将枚举结果转换为列表:

list(enumerate(fruits))
[(0, 'apple'), (1, 'banana'), (2, 'orange')]

while循环:条件驱动重复执行

while循环在条件为真时持续运行,需注意避免无限循环(也就是常说的死循环):

while condition:
    # 执行的代码块
示例:计数到指定值
1
2
3
4
count = 0
while count < 3: # 输出0到2
    print(count)
    count += 1  # 等同于count = count + 1

也可以支持多条件的情况

1
2
3
4
5
6
7
8
9
count = 0
max_count = 5
user_quit = False

while count < max_count and not user_quit:
    print(count)
    count += 1
    if count == 3:
        user_quit = True  # 模拟用户退出

循环控制语句:break与continue

  • break立即终止当前循环:

    1
    2
    3
    4
    for num in [1, 2, 3, 4]:
        if num == 3:
            break  # 当num为3时退出循环
        print(num,end=" ")
    
    1 2 
    

  • continue跳过当前迭代,进入下一次循环:

    1
    2
    3
    4
    for num in [1, 2, 3, 4]:
        if num == 3:
            continue  # 跳过打印3
        print(num,end=" ")
    
    1 2 4 
    

嵌套循环与else子句

嵌套循环用于处理多维数据,如矩阵遍历:

1
2
3
for i in range(3):
    for j in range(2):
        print(f"({i}, {j})")
1
2
3
4
5
6
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

循环的else子句在循环正常结束后执行(非break中断时触发):

1
2
3
4
5
6
for n in range(2, 4):
    if n == 3:
        print("触发break,else不执行")
        break
else:
    print("循环正常结束")

实际应用场景

文件处理:逐行读取文件内容

1
2
3
with open("data.txt") as file:
    for line in file:
        print(line.strip())
其中strip是 Python 字符串方法,用于移除字符串首尾的空白字符,空白字符包括:空格 " ",制表符 \t, 换行符 \n, 回车符 \r

数据过滤:结合条件语句筛选列表

1
2
3
4
numbers = [10, 20, 30, 40]
filtered = [x for x in numbers if x > 25]  # 列表推导式
print(filtered)
# 也就是依次遍历每个x,如果x满足大于25就留下
[30, 40]

掌握循环语句是Python编程的基础,灵活运用可大幅提升代码效率。建议通过实际项目练习巩固理解!