中断并继续运行 [英] break and continue in function

查看:96
本文介绍了中断并继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def funcA(i):
   if i%3==0:
      print "Oh! No!",
      print i
      break

for i in range(100):
   funcA(i)
   print "Pass",
   print i

我知道上面的脚本不起作用.那么,如果需要将带有break的函数或继续放入循环中,该如何写?

解决方案

一个函数不能在调用它的代码中引起中断或继续.中断/继续必须从字面上出现在循环内.您的选择是:

  1. 从funcA返回一个值,并用它来决定是否破坏
  2. 在funcA中引发异常并将其捕获在调用代码中(或调用链中更高的位置)
  3. 编写一个生成器,该生成器封装中断逻辑,然后在range
  4. 上对其进行迭代

通过#3,我的意思是这样的:

def gen(base):
    for item in base:
        if item%3 == 0:
           break
        yield i

for i in gen(range(1, 100)):
    print "Pass," i

这允许您通过将条件分组到基于基本"迭代器(在此情况下为范围)的生成器中来放置条件.然后,您在此生成器上进行迭代,而不是在范围本身上进行迭代,您会得到破坏行为.

def funcA(i):
   if i%3==0:
      print "Oh! No!",
      print i
      break

for i in range(100):
   funcA(i)
   print "Pass",
   print i

I know script above won't work. So, how can I write if I need put a function with break or continue into a loop?

解决方案

A function cannot cause a break or continue in the code from which it is called. The break/continue has to appear literally inside the loop. Your options are:

  1. return a value from funcA and use it to decide whether to break
  2. raise an exception in funcA and catch it in the calling code (or somewhere higher up the call chain)
  3. write a generator that encapsulates the break logic and iterate over that instead over the range

By #3 I mean something like this:

def gen(base):
    for item in base:
        if item%3 == 0:
           break
        yield i

for i in gen(range(1, 100)):
    print "Pass," i

This allows you to put the break with the condition by grouping them into a generator based on the "base" iterator (in this case a range). You then iterate over this generator instead of over the range itself and you get the breaking behavior.

这篇关于中断并继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆