Skip to content

Python 循环

Python 中常用的循环有两种:forwhile

  • for:用于遍历序列或可迭代对象中的元素(如字符串、列表、元组、集合、字典的键值对等)。
  • while:在条件为真时反复执行循环体;条件变为时结束(不是「直到为 False 才执行」——条件为假时停止)。
  • for 几乎总是配合 in 使用,逐个取出可迭代对象中的元素。
  • breakcontinue 用于在循环体内改变流程(提前结束循环、跳过本次剩余语句)。
  • 循环可以嵌套for 里再写 for / while 等)。
  • for / while 都可以带 else 子句:在循环未被 break 打断、自然结束后执行;若由 break 跳出,则不执行 else。循环体内未捕获的异常也会导致 else 不执行。

更细的 while 用法见 while 循环break / continuebreak 语句continue 语句

语法概要

for 循环

python
for element in sequence:
    # 循环体
else:  # 可选:循环正常结束时执行
    # else 块

while 循环

python
while condition:
    # 循环体
else:  # 可选:循环正常结束时执行
    # else 块

for 循环示例

1. 遍历字符串

shell
>>> text = "Python"
>>> for c in text:
...     print(c)
...
P
y
t
h
o
n

(示例中变量名不用 str,以免覆盖内置类型 str。)

2. 遍历元组

shell
>>> t = (1, 2, 3)
>>> for i in t:
...     print(i)
...
1
2
3

3. 遍历列表

shell
>>> fruits = ["Apple", "Banana", "Grapes"]
>>> for fruit in fruits:
...     print(fruit)
...
Apple
Banana
Grapes

列表的更多操作见 列表

4. 遍历集合

shell
>>> my_set = set("ABCBA")
>>> for c in my_set:
...     print(c)
...

集合没有固定顺序,多次运行同一脚本时,打印顺序可能不同。

5. 遍历字典

常用 dict.items() 同时得到键和值(在 for 中解包为两个变量):

shell
>>> num_dict = {1: "one", 2: "two", 3: "three"}
>>> for k, v in num_dict.items():
...     print(f"{k}={v}")
...
1=one
2=two
3=three

只遍历键可用 for k in num_dict:,只遍历值可用 for v in num_dict.values():

while 循环示例

1. 固定次数

shell
>>> count = 5
>>> while count > 0:
...     print("run this code")
...     count -= 1
...
run this code
run this code
run this code
run this code
run this code

2. 条件由随机数更新

下面每次循环用 random.randint 更新 count,循环次数不固定,直到 count >= 10

python
import random

count = 0
while count < 10:
    print("print this random times")
    count = random.randint(0, 12)

循环上的 else 子句

else 在循环完整跑完(未遇 break)时执行。若循环体内抛出未处理的异常,同样不会执行该 else

forelse

python
for i in (1, 2):
    pass
else:
    print("1. for 循环正常结束")

for i in (1, 2):
    try:
        raise ValueError
    except ValueError:
        pass
else:
    print("2. for 循环正常结束")

try:
    for i in (1, 2):
        raise ValueError
    else:
        print("3. for 循环正常结束")
except ValueError:
    print("4. 捕获到 ValueError,未进入上一行的 else")

要点:第三个例子中,ValueErrorfor 体内抛出且未被该 for 内部捕获,因此不会打印 3.,而是由外层 except 处理。

whileelse

python
count = 0
while count < 5:
    pass
    count += 1
else:
    print("1. else 块:while 条件变为假后执行")

count = 0
try:
    while count < 5:
        raise ValueError
        count += 1
    else:
        print("2. else 块")
except ValueError:
    print("3. except 块:循环体内异常,不执行 while 的 else")

breakcontinue

  • break:立即结束当前这一层循环。
  • continue:跳过本次循环体剩余语句,进入下一轮判断。

break 示例

python
ints = [1, 2, 3, 5, 4, 2]

for i in ints:
    if i > 4:
        break
    print(i)

输出:123(遇到 5break)。

continue 示例

python
def process_even_ints(ints_list):
    for i in ints_list:
        if i % 2 != 0:
            continue
        print("Processing", i)


process_even_ints([1, 2, 3, 4, 5])

输出:

text
Processing 2
Processing 4

嵌套循环

内层、外层可以任意组合 for / while。下面遍历「外层序列」的每个元素,再对内层可迭代对象逐元素处理(字符串会按字符迭代):

python
nested_sequence = ["01", (2, 3), [4, 5, 6]]

for x in nested_sequence:
    for y in x:
        print(y)

会依次打印:0123456

小结

  • for ... in ... 适合已知可迭代对象的遍历;while 适合由条件控制的重复执行。
  • break / continue 控制循环流程;else 挂在循环上时表示「正常跑完未 break」时的收尾逻辑。
  • 需要随机次数、复杂条件时,可结合 import random 等与 函数 一起使用。

参考