在python中从for循环中断

时间:2014-05-17 19:51:51

标签: python loops for-loop break

我在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之前不会中断?

2 个答案:

答案 0 :(得分:2)

您应该注意winhwinw永远不会超出预期的最大值。为确保这一点,您需要在实际更改窗口大小之前测试值加上stepsize不超过最大值。

其他人提供的解决方案(使用>=或更改执行顺序)只会以10的倍数开始解决您的问题。请尝试以下方法。我冒昧地调整了你的代码。

winw = 60
winh = 40
stepsize = 10
for i in range(num_scale_steps):
    if (winh + stepsize > 360) or(winw + stepsize > 240) :
        break
    print "in iteration %d " % i
    winw += stepsize
    winh += stepsize
    print "new width:%d"   % winw

答案 1 :(得分:1)

试试这个:

  winw = 60
    winh = 40
    for i in range(num_scale_steps):
        if (winh > 360) or(winw > 240) :
            break
        print "in iteration %d " % i
        winw = 10 + winw
        winh = 10 + winh
        print "new width:%d"   % winw

您需要在打印新值之前检查条件。