【发布时间】:2023-11-24 09:41:01
【问题描述】:
我在 for 循环中使用了 break 命令,但它似乎不起作用。
这是我的代码:
winw = 60
winh = 40
for i in range(num_scale_steps):
print "in iteration %d " % i
# some code that will crash if winw > 240
winw = 10 + winw
winh = 10 + winh
print "new width:%d" % winw
if (winh > 360) or(winw > 240) :
break
但它不会中断。它给出的最后输出是:
new width 240
in iteration 18
new width:250 --> at this point it should break and not continue to next iteration
in iteration 19
# then it crashes because winw > 240
250 大于 240。但是为什么循环在迭代 19 之前没有中断?
【问题讨论】:
-
它确实在 winw = 250 之后立即中断(这是最后一次打印,然后中断)。再次检查。
-
如果您希望它在上一次迭代中中断,您需要使用
>=而不是> -
尝试只运行您提供的代码。没有迭代 19.
-
是的,代码的行为与您描述的不同。
-
无法重现您的结果,请再次检查您的代码。
标签: python loops for-loop break