Python继续无法正常工作

时间:2016-07-21 16:53:45

标签: python for-loop continue

我正在使用Python编写一个方法,我相信continue语句无法正常工作。有人可以向我解释那里有什么问题吗?

方法代码如下:

def xlToLinkedDt(lst1, lst2, name1, name2):
        logging.info(">> New iteration")
        dates1, times1, dates2, times2 = [], [], [], []
        for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
            if bool(dt1) + bool(dt2) == 1:
                name = name1 if not dt1 else name2
                issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
                dates1.append("")
                dates2.append("")
                times1.append("")
                times2.append("")
                logging.info("Exiting loop")
                continue

            logging.info(Continued after bool condition.)
            raise AssertionError("Stop!")

当我运行此代码时,我收到一个错误,并在其中一个迭代中记录以下内容:

>> New iteration
>> Exiting loop
>> Continued after bool condition

代码不应该记录两条消息,只记录其中一条消息。此外,当我用continue替换break时效果很好。我错过了什么?

2 个答案:

答案 0 :(得分:2)

  

代码不应该记录这两个消息。

是的,是的。

在代码执行 continue 之后,循环在下一次迭代中移回到for循环内的块的开头。如果在下一次迭代中未满足if - 块中的条件,您将获得您描述的行为。

In [5]: for i in range(10):
    print("Trying with i={:d}".format(i))
    if i%2 == 0:
        print("`i` even, continuing")
        continue
    print("What am I doing here?")
   ...:     
Trying with i=0
`i` even, continuing
Trying with i=1
What am I doing here?
Trying with i=2
`i` even, continuing
Trying with i=3
What am I doing here?
Trying with i=4
`i` even, continuing
Trying with i=5
What am I doing here?
Trying with i=6
`i` even, continuing
Trying with i=7
What am I doing here?
Trying with i=8
`i` even, continuing
Trying with i=9
What am I doing here?

正如您所看到的, i偶数,继续通知后仍然会显示我在做什么?,但它属于稍后迭代循环。如果我们将continue替换为break,我们会得到非常不同的行为:

In [6]: for i in range(10):
    print("Trying with i={:d}".format(i))
    if i%2 == 0:
        print("`i` even, not continuing")
        break   
    print("What am I doing here?")
   ...:     
Trying with i=0
`i` even, not continuing

如您所见,它会立即停止,因为(根据我们的定义),0是偶数。

答案 1 :(得分:0)

您使用了continue,我想您的意思是break

continue将跳到for循环的下一次迭代。 break将离开for循环。

试试:

def test():
    print("Function start")
    for i in range(10):
        if i == 1:
            print("Exiting loop")
            continue

        print("Am I printed or not ?")
    print("I'm out of the loop")

然后将continue替换为break,看看会发生什么。 由于print("Am I printed or not ?")for循环的一部分,因此如果使用continue,它将在“退出循环”之后的下一次迭代执行。如果您使用break,则会跳过它。