问题描述
所以我在 Python 中试验 for 循环,我决定让我使用 continue 和 break 语句进行试验,我知道有什么区别。所以“break”完全退出你的循环,“continue”跳过循环的当前迭代并继续它,但是当我在嵌套循环中尝试“break”和“continue”时头痛开始了,我发现代码没有区别我在下面粘贴了
1.)“中断”嵌套循环。
for i in range(6):
print("iteration {}".format(i))
for j in range(6):
if i == 3:
break
print(j)
2.) “继续”嵌套循环
for i in range(6):
print("iteration {}".format(i))
for j in range(6):
if i == 3:
continue
print(j)
我的问题是为什么“继续”和“中断”在我的代码中的嵌套循环中的行为相同???
对于那些想知道循环输出的人
1.) 用于“中断”
iteration 0
0
1
2
3
4
5
iteration 1
0
1
2
3
4
5
iteration 2
0
1
2
3
4
5
iteration 3
iteration 4
0
1
2
3
4
5
iteration 5
0
1
2
3
4
5
2.)“继续”的输出
iteration 0
0
1
2
3
4
5
iteration 1
0
1
2
3
4
5
iteration 2
0
1
2
3
4
5
iteration 3
iteration 4
0
1
2
3
4
5
iteration 5
0
1
2
3
4
5
对答案会有很大帮助!!...thanksss..
解决方法
break
版本:
当 i == 3
时,break
在 第一次 迭代中脱离 j
循环,因此它什么都不做。
continue
版本:
当 i == 3
时,continue
在 每次 迭代的 j
调用之前返回到 print()
循环的顶部,因此 { {1}} 调用没有发生。