Skip to main content
 首页 » 编程设计

python之如何正确打破这个循环

2024年11月01日9hnrainll

我对如何纠正以下问题有点迷茫。 当 xxxx 计数器达到 15 时,我希望脚本停止,效果很好。 但是,当其中一个 try 语句出现错误时,我只希望它转到旧列表中的下一个 url,而不是像现在这样停止脚本。

我阅读了有关此内容的文档以及可能更好地包含 While 语句,但我不确定在这里该怎么做才能让它像我想要的那样工作。它实际上是一个更大的循环,但在下面进行了简化。

系统:Python 2.7.* x64 上的 IDLE

xxxx = 0 
oldlist = [lost of stuff] 
newlist = [lots of stuff] 
otherlist = [lots of stuff] 
 
for url in oldlist: 
    found = False 
 
    if xxxx == 15: 
        break 
 
    for item in newlist: 
        if something: 
            if something: 
                found = True 
 
    for items in otherlist: 
        if something: 
            found = False 
 
    if found == True: 
        xxxx +=1 
 
        try: 
            something 
        except Exception as thing: #catch em all 
            print "1st Error" 
            break    #should go to the next url 
 
        try: 
            something 
        except Exception as morethings: #catch em all 
            print "2nd Error" 
            break    #should go to the next url 

这真的是糟糕的 python 吗? 应该更像:

while xxxx != 15: 
    for url in oldlist: 
        found = False 
 
        for item in newlist: 
            if something: 
                if something: 
                    found = True 
 
        for items in otherlist: 
            if something: 
                found = False 
 
        while found == True: 
            xxxx +=1 
 
        while True: 
            try: 
                something 
            except Exception as thing: #catch em all 
                print "1st Error" 
                break 
 
            try: 
                something 
            except Exception as morethings: #catch em all 
                print "2nd Error" 
                break 

请您参考如下方法:

如果我理解你的问题,你需要 continue 语句,而不是 break 语句。

Flow-control docs