Skip to content

循环语句

本章节将为大家介绍 Python 循环语句的使用。

Python 中的循环语句有 for 和 while。

Python 循环语句的控制结构图如下所示:

while 循环

while 循环是一种最基本的循环语句。

语法格式如下:

python
while 表达式:
    语句

表达式是一个布尔表达式,如果表达式为 True,则执行语句,否则跳过语句块,继续执行循环。

python
count = 0
while count < 5:
    print(count)
    count += 1

输出:

0
1
2
3
4

无限循环

如果 while 循环条件永远为 True,则循环将无限执行下去,称为无限循环。

python
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

while 循环使用 else 语句

while 循环还可以使用 else 语句,该语句在循环正常执行完(即 while 表达式为 False)时执行。

python
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("循环结束")

输出:

0
1
2
3
4
循环结束

for 循环

for 循环是一种迭代循环语句,可以遍历任何序列的元素。 语法格式如下:

python
for 变量 in 序列:
    语句

变量是循环过程中迭代的元素,序列可以是列表、元组、字符串、字典等。

python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

输出:

apple
banana
orange

for 循环使用 else 语句

for 循环还可以使用 else 语句,该语句在循环正常执行完(即 for 循环正常结束)时执行。遇到了 break 语句,则会中断循环,此时不会执行 else 子句。

python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)
else:
    print("循环结束")

输出:

apple
banana
orange
循环结束

嵌套循环

for 循环可以嵌套,即一个 for 循环中包含另一个 for 循环。

python
for i in range(3):
    for j in range(2):
        print(i, j)

输出:

0 0
0 1
1 0
1 1
2 0
2 1

range() 函数

如果你需要遍历数字序列,可以使用内置 range() 函数。它会生成数列,例如:

python
for i in range(5):
    print(i)

输出:

0
1
2
3
4

range() 函数可以接收三个参数,第一个参数指定开始值,第二个参数指定结束值(不包含),第三个参数指定步长。

python
for i in range(2, 10, 2):
    print(i)

输出:

2
4
6
8

break 语句

break 语句可以提前结束循环。

python
for i in range(5):
    if i == 3:
        break
    print(i)

输出:

0
1
2

break,continue 语句和循环中的 else 语句

break 执行流程图:

continue 执行流程图:

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

pass 语句

pass 语句什么都不做,一般用做占位语句。