在python中重启一个函数

时间:2016-07-23 14:34:58

标签: python loops if-statement while-loop break

我的代码是一段时间的True循环。 它基本上尝试像验证码。

所以我想要的是这样的

def  loop():
    toplam = 0
    global sayilar
    x = br.open(something)
    html = x.read()
    sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
    print sayilar
    for i in sayilar:
        if i in diction:
            toplam += diction[i]
        else 
            #break the function








if __name__ == "__main__":
    giris()
    while 1:
        loop()

它无法在字典中找到它会破坏函数并再次重启函数的数字,因为函数处于while循环中。

2 个答案:

答案 0 :(得分:0)

好的找到了重启它的好方法。

class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg
def  loop():
    toplam = 0
    global sayilar
    x = br.open(something)
    html = x.read()
    sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
    print sayilar
    for i in sayilar:
        if i in diction:
            toplam += diction[i]
        else 
            raise CustomError('Kelime Dictionaryde bulunamadi')








if __name__ == "__main__":
    giris()
    while 1:
        try:
            loop()
        except CustomError, arg:
            print "Can't find in dictionary"

答案 1 :(得分:0)

您可以逐字地使用break。通过使用break,您可以立即停止循环。您稍后会看到使用return

for i in sayilar:
    if i in diction:
        toplam += diction[i]
    else: 
        return None
        break
return True                # Anything but None will work in place of True

while循环的内容相同:

while True:    # Use True instead of 1
    loop()
    if loop() == None:            # The function call is equal to what it returned
        break
    else:
        continue                   # Optional else statement: continues loop if loop() != None