摘要:在本节中,你将学习 Python 的 continue
语句以及如何使用它来控制循环。
Python continue
语句简介
continue
语句用于 for
循环或 while
循环内部continue
语句会跳过当前迭代,并开始下一次迭代。
通常,你会将 continue
语句与 if
语句一起使用,以便在条件为真时跳过当前迭代。
以下展示了如何在 for
循环中使用 continue
语句:
for index in range(n):
if condition:
continue
# more code here
以下说明了如何在 while
循环中使用 continue
语句:
while condition1:
if condition2:
continue
# more code here
在 for
循环中使用 continue
的示例
以下示例展示了如何使用 for
循环显示从 0 到 9 的偶数:
for index in range(10):
if index % 2:
continue
print(index)
输出:
0
2
4
6
8
工作原理:
首先,使用带有
range()
函数的for
循环遍历从 0 到 9 的数字范围。其次,如果索引是奇数,则跳过当前迭代并开始新的迭代。注意,如果索引是奇数
index % 2
返回 1;如果索引是偶数index % 2
返回 0。
在 while
循环中使用 continue
的示例
以下示例展示了如何使用 continue
语句将 0 到 9 之间的奇数显示到屏幕上:
# print the odd numbers
counter = 0
while counter < 10:
counter += 1
if not counter % 2:
continue
print(counter)
输出:
1
3
5
7
9
工作原理:
首先,定义一个计数器变量,并将其初始值设为零。
其次,只要计数器小于 10,就启动循环。
第三,在循环内部,每次迭代时将计数器加 1。如果计数器是偶数,则跳过当前迭代;否则,将计数器显示到屏幕上。
总结
使用 Python 的
continue
语句可以跳过当前迭代并开始下一次迭代。