我怎样才能跳到另一个循环?
How can I jump to another loop?
我有问题。我不知道如何跳转到另一个循环。我应该在当前循环中使用 'continue' 还是 'break' ? (python3.x)
While True: <-- continue to this
While True:
continue <-- continue to the first while loop
可以打破内循环继续外循环
while True:
while True:
# do some checks if you want to
break
break
关键字允许您退出您所在的主循环。所以如果您有这样的语句:
while True:
while True:
break
中断会让你回到第一个循环。
按照建议使用 break 当满足条件时退出内部循环。考虑来自[这里https://docs.python.org/3/tutorial/controlflow.html][1]
的这个例子
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
结果
2是质数
3是质数
4 等于 2 * 2
5是质数
6 等于 2 * 3
7是质数
8 等于 2 * 4
9 等于 3 * 3
我有问题。我不知道如何跳转到另一个循环。我应该在当前循环中使用 'continue' 还是 'break' ? (python3.x)
While True: <-- continue to this
While True:
continue <-- continue to the first while loop
可以打破内循环继续外循环
while True:
while True:
# do some checks if you want to
break
break
关键字允许您退出您所在的主循环。所以如果您有这样的语句:
while True:
while True:
break
中断会让你回到第一个循环。
按照建议使用 break 当满足条件时退出内部循环。考虑来自[这里https://docs.python.org/3/tutorial/controlflow.html][1]
的这个例子for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
结果 2是质数 3是质数 4 等于 2 * 2 5是质数 6 等于 2 * 3 7是质数 8 等于 2 * 4 9 等于 3 * 3