Home  >  Q&A  >  body text

python - Looking for a method in def that can achieve the continue effect of calling this def to meet specific conditions (the title is not clear, please see the description in the question)

def con(x):
    if x==3:
        continue #会报错

def con2(x):
    if x == 4:
        continue #会报错
for i in range(0,10):
    con(i)
    con2(i)
    print(i)
    

What I mean is that if the conditions in def are met, the externally called for loop will continue. For example, in the example, if the value of i is 3 or 4, continue. Because there are many def methods called in for, and the actual scenario is much more complicated than the example, it feels like it is not very concise to judge the return value one by one. I would like to ask you if there is any way to realize this request of my brother. Thank you very much~

过去多啦不再A梦过去多啦不再A梦2672 days ago724

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-27 17:41:54

    You can affect the for loop by throwing a specific exception:

    
    class Abort(Exception):
        pass
    
    def con(x):
        if x==3:
            raise Abort()
    
    def con2(x):
        if x == 4:
            raise Abort()
    for i in range(0,10):
        try:
            con(i)
            con2(i)
        except Abort:
            continue
        print(i)
        

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-27 17:41:54

    continue must be used together with for. You can try another implementation idea
    such as:

    def con(x):
        return True if x == 3 else False
    
    def con2(x):
        return True if x == 4 else False
    
    for i in range(0,10):
        lst = [
            con(i),
            con2(i)
        ]
        
        if any(lst):
            continue
    
        print(i)

    reply
    0
  • Cancelreply