如何使用try-except语句突破for循环?

时间:2019-06-28 10:39:51

标签: python loops for-loop iteration

我有一个for循环,其中引用了https://machinetalk.org/2019/03/29/neural-machine-translation-with-attention-mechanism/?unapproved=67&moderation-hash=ea8e5dcb97c8236f68291788fbd746a7#comment-67:-的try-except块摘录

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break

我想退出循环,而不执行try块,而保留所有内容,而直接退出内部和外部循环以及整个try-except块。我不知道出了什么问题,因为在内/外循环块中使用if条件不起作用。

1 个答案:

答案 0 :(得分:1)

this answer所述,这可能是嵌套循环的问题。他们建议使用return,但是您的循环将需要作为一个函数编写。如果那没有吸引力,您可以尝试使用各种级别的break语句,如一些答案中所示。使用for,else结构(explained here),我认为您的代码将如下所示

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break
else:
    continue ###executed if inner loop did NOT break
break  ###executed if inner loop DID break